user1894208
user1894208

Reputation: 41

Understanding Python's backslash escape character

My script creates files to export by concatenating a file path with a file type suffix. For example,

int = 3
print r"C:\Test\\" + str(int) + ".jpg"

This returns C:\Test\\3.jpg

I thought that because I included the 'r' at the beginning, I wouldn't need a double backslash at the end, because it'd be treated as a raw string. But the following doesn't work:

int = 3
print r"C:\Test\" + str(int) + ".jpg"

...presumably because Python is seeing an escape character before the end quote. So what's the point of the 'r' then? And while my files get saved in the right place when exported, I don't like that the print command gives me two backslashes after Test (eg C:\Test\3.jpg) when it just gives me one after C:

How can I get a single backslash in my file paths please?

Upvotes: 3

Views: 1419

Answers (3)

viprs
viprs

Reputation: 337

first, don't call an integer int, as it shadows the built-in int() function.
use os.path is a very clever way:

import os.path
i = 3
print os.path.join("C:\Test", str(i) + ".jpg")
#C:\Test\3.jpg

OR U must use strings to manipulation to build up file paths:

_prefix = 'C:\Test'
i = 3
print _prefix + '\\' + str(i) + '.jpg'
#C:\Test\3.jpg

Upvotes: 0

poke
poke

Reputation: 387557

Even in a raw string, string quotes can be escaped with a backslash, but the backslash remains in the string; for example, r"\"" is a valid string literal consisting of two characters: a backslash and a double quote; r"\" is not a valid string literal (even a raw string cannot end in an odd number of backslashes). Specifically, a raw string cannot end in a single backslash (since the backslash would escape the following quote character). Note also that a single backslash followed by a newline is interpreted as those two characters as part of the string, not as a line continuation.

Source.

So, it won’t work like that. If you want to use a raw string, but have a trailing backslash, you need to add that separately afterwards:

>>> r'C:\Test' + '\\'
'C:\\Test\\'

Alternatively, in your case, you can also just use string formatting to insert your values:

>>> r'C:\Test\{0}.jpg'.format(i)
'C:\\Test\\1.jpg'

Or, you use os.path.join to build the path:

>>> os.path.join(r'C:\Test', str(i) +'.jpg')
'C:\\Test\\1.jpg'

Upvotes: 5

Daniel Roseman
Daniel Roseman

Reputation: 599490

Don't try and use string manipulation to build up file paths. Python has the os.path module for that:

import os.path
i = 3
print os.path.join("C:\Test", str(i) + ".jpg")

This will ensure the path is constructed properly.

(Also, don't call an integer int, as it shadows the built-in int() function.)

Upvotes: 6

Related Questions