简体   繁体   中英

how to type "\ as a string in python

I writing a python program for Windows. The path consists of the foldername + filename, where the filename changes in each iteration. The folder address is always the same so I write the code as:

 path =  "%s%s" % ("C:\Users\ME\raw_image\", filename)

However I have noticed that the character \\" is considered as escape and also \\r is problematic. I tried a couple of things but could not figure out how to get rid of this issue.

Any ideas?

You have two options. Either use a raw string for the folder path:

path =  r"%s\%s" % (r"C:\Users\ME\raw_image", filename)

or escape the backslashes using a backslash:

path =  "%s%s" % ("C:\\Users\\ME\\raw_image\\", filename)

As noted by @Erik-Sun, using raw strings requires special handling of the a trailing backslash, ie trying r"C:\\Users\\ME\\raw_image\\" will cause a syntax error because Python will interpret the trailing backslash as an escape on the double-quote.

To get around this I simply moved the last backslash to the unformated string r'%\\%' .

Use \\\\ instead of \\ in your code, like this example:

>>> print("C:\\Users\\Me\\raw_image\\")
C:\Users\Me\raw_image\

你可以像这样添加另一个反斜杠:

path =  "%s%s" % ("C:\\Users\\ME\\raw_image\\", filename)

I would rather suggest you to use the str.format() function, because this avoids you to 'escape' the backslash.

eg

>>> filename = "filename.txt"
>>> path = "C:\\Users\\Me\\raw_image\\{}".format(filename)
>>> print(path)

output will be:

C:\\Users\\Me\\raw_image\\filename.txt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM