Problem with split() command

I have run below statement

</>
x = ‘d:\level1\test.exe’
print(x.isspace())
result = x.split(‘\’)
for i in result:
print(i)
</>

and expected the come out is:
False
d:
level1
test.exe

but finally the come out is:

False
d:
level1 est.exe

What is the problem? It looks like the characters ‘\t’ recognized as [TAB]. How can I correct the problem?

I am using Python 3.9 with PyCharm 2022.3.2

Please edit your code (pencil icon) to replace </> with

```

It does not read right as is.

Yes, that is the problem. It has nothing to do with .split, the string is not created properly in the first place.

By creating the string properly, using escape sequences where needed. Specifically, to put an actual backslash in the string, double it up in the source code. Note that you must also use this for the delimiter for the .split call: x.split('\\'). The code that you showed should not be accepted at all (but maybe it just got messed up when you tried to post it).

However, you should also be aware that on Windows, it is not necessary, and generally not a good idea, to use backslashes for file paths even though that is what DOS uses. Just write a forward slash; it will be translated for you automatically behind the scenes.

1 Like

In addition: if you are trying to work with pathnames, then you should use the os.path module.

Or pathlib, which is newer and offers a higher-level interface.

4 Likes

Correct.

In addition to the various suggestions already, if I working with
strings containing backslashes such as Windows pathnames or regular
expressions I try to use 'raw strings", which prefix the leading quote
with an “r”, example:

 path = r'd:\foo\text.txt'

Inside a raw string the backslash is not special. This means:

  • you do not need to double them to get a backslash
  • you don’t need to handle eg \t specially

A “raw string” is just Python code notation - the result is still a
normal string.

Cheers,
Cameron Simpson cs@cskk.id.au

Problem solved. Thanks.:grinning::grinning:

Cameron Simpson via Discussions on Python.org <notifications@python1.discoursemail.com> 於 2023年4月4日 週二 上午7:22寫道: