Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
506 views
in Technique[技术] by (71.8m points)

How to get rid of double backslash in python windows file path string?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The double backslash is not wrong, python represents it way that to the user. In each double backslash \, the first one escapes the second to imply an actual backslash. If a = r'raw sring' and b = 'raw s\tring' (no 'r' and explicit double slash) then they are both represented as 'raw s\tring'.

>>> a = r'raw sring'
>>> b = 'raw s\tring'
>>> a
'raw s\tring'
>>> b
'raw s\tring'

For clarification, when you print the string, you'd see it as it would get used, like in a path - with just one backslash:

>>> print(a)
raw sring
>>> print(b)
raw sring

And in this printed string case, the doesn't imply a tab, it's a backslash followed by the letter 't'.

Otherwise, a string with no 'r' prefix and a single backslash would escape the character after it, making it evaluate the 't' following it == tab:

>>> t = 'not raw sring'  # here '' = tab
>>> t
'not raw sring'
>>> print(t)  # will print a tab (and no letter 't' in 'sring')
not raw s       ring

So in the PDF path+name:

>>> item = 'xyz'
>>> PDF = r'C:UsersuserDesktopFile_%s.pdf' % item
>>> PDF         # the representation of the string, also in error messages
'C:\Users\user\Desktop\File_xyz.pdf'
>>> print(PDF)  # "as used"
C:UsersuserDesktopFile_xyz.pdf

More info about escape sequences in the table here. Also see __str__ vs __repr__.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...