Concatenate backslash on python

Vini.g.fer picture Vini.g.fer · Apr 1, 2014 · Viewed 17.9k times · Source

I'm new to python so forgive me if this sounds simple. I want to join a few variables to produce a path. Like this:

AAAABBBBCCCC\2\2014_04\2014_04_01.csv

Id + '\' + TypeOfMachine + '\' + year + '_' + month + '\' + year + '_' + month + '_' + day + '.csv'

How do I concatenate this? I putted single quotes around underline or backslash, but stackoverflow omits/modifies them.

Answer

kojiro picture kojiro · Apr 1, 2014

A backslash is commonly used to escape special strings. For example:

>>> print "hi\nbye"
hi
bye

Telling Python not to count slashes as special is usually as easy as using a "raw" string, which can be written as a string literal by preceding the string with the letter 'r'.

>>> print r"hi\nbye"
hi\nbye

Even a raw string, however, cannot end with an odd number of backslashes. This makes string concatenation tough.

>>> print "hi" + r"\" + "bye"
File "<stdin>", line 1
print "hi" + r"\" + "bye"
                       ^
SyntaxError: invalid syntax

There are several ways to work around this. The easiest is using string formatting:

>>> print r'{}\{}'.format('hi', 'bye')
hi\bye

Another way is to use a double-backslash in a regular string to escape the second backslash with the first:

>>> print 'hi' + '\\' + 'bye'
hi\bye

But all of this assumes you're facing a legitimate need to use backslashes. If all you're trying to do is construct Windows path expressions, just use os.path.join.