Prelude
Prelude

Reputation: 151

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?

Upvotes: 1

Views: 1913

Answers (4)

Anie bo
Anie bo

Reputation: 13

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

e.g.

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

output will be:

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

Upvotes: 1

James
James

Reputation: 36623

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, i.e. 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'%\%'.

Upvotes: 4

Ridouane Hadj Aissa
Ridouane Hadj Aissa

Reputation: 21

you can add another backslash like this:

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

Upvotes: 2

Hossein Torabi
Hossein Torabi

Reputation: 733

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

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

Upvotes: 2

Related Questions