Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate backslash on python

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.

like image 888
Vini.g.fer Avatar asked Apr 01 '14 16:04

Vini.g.fer


1 Answers

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.

like image 125
kojiro Avatar answered Sep 22 '22 09:09

kojiro