Albert
(Albert Yam)
April 3, 2023, 6:22am
1
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
tjreedy
(Terry Jan Reedy)
April 3, 2023, 6:34am
2
Please edit your code (pencil icon) to replace </>
with
```
It does not read right as is.
kknechtel
(Karl Knechtel)
April 3, 2023, 6:54am
3
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
rob42
(Rob)
April 3, 2023, 7:33am
4
In addition: if you are trying to work with pathnames, then you should use the os.path module.
abessman
(Alexander Bessman)
April 3, 2023, 7:38am
5
Or pathlib , which is newer and offers a higher-level interface.
4 Likes
cameron
(Cameron Simpson)
April 3, 2023, 11:12pm
6
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
Albert
(Albert Yam)
April 5, 2023, 11:04am
7
Problem solved. Thanks.
Cameron Simpson via Discussions on Python.org <notifications@python1.discoursemail.com > 於 2023年4月4日 週二 上午7:22寫道: