Reputation: 1
I am trying to store a string in variable A
which contains:
"'D:\\Work\\B1.tif';'D:\\Work\\B2.tif'"
I have two variables that store the locations of B1.tif
and B2.tif
:
X = "D:\\Work\\B1.tif"
Y = "D:\\Work\\B2.tif"
However, when I try to combine all the strings into a variable 'A':
A = '"' + "'" + X + "'" + ";" + "'" + Y + "'" + '"'
This is what it stores as:
'"\'D:\\Work\\B1.tif\';\'D:\\Work\\B2.tif\'"'
When I print
A
it displays:
"'D:\Work\B1.tif';'D:\Work\B2.tif'"
It seems that a backslash (\
), that separates double quotes ("
) and single quotes ("
), are automatically stored in the string. How do I store double quotes and single quotes in a string without the backslash separating the quotes?
Upvotes: 0
Views: 142
Reputation: 922
When you display a variable in Python by just typing it's name, Python tries to print it in a way that if you were to copy and paste it as a variable, it would produce the same object. This works for strings, lists, dictionaries, sets, etc. The consequence is that strings need to be escaped when printed out this way. The backlashes are not actually stored in the string. You can see that by calculating the length:
>>> a = '"' + "'"
>>> a
'"\''
>>> len(a)
2
>>> print a
"'
There are, however, better ways to build the same string you want, as shown by the other answers.
Upvotes: 1
Reputation: 44354
String formatting (and raw strings) is much easier:
A = "\"'D:\\Work\\B1.tif';'D:\\Work\\B1.tif'\""
print A
X = r"D:\Work\B1.tif"
Y = r"D:\Work\B2.tif"
A = '"' + "'" + X + "'" + ";" + "'" + Y + "'" + '"'
print A
A = "\"'%s';'%s'\"" % (X, Y)
print A
Gives:
"'D:\Work\B1.tif';'D:\Work\B1.tif'"
"'D:\Work\B1.tif';'D:\Work\B2.tif'"
"'D:\Work\B1.tif';'D:\Work\B2.tif'"
However, to get the results you show, you have to use repr()
, which is what IDLE uses if you just type the variable name in. If I change all the print
statements to print repr(A)
I get:
'"\'D:\\Work\\B1.tif\';\'D:\\Work\\B1.tif\'"'
'"\'D:\\Work\\B1.tif\';\'D:\\Work\\B2.tif\'"'
'"\'D:\\Work\\B1.tif\';\'D:\\Work\\B2.tif\'"'
IDLE uses the class's __repr__()
method, print
uses __str__()
. Often they are the same, but sometime, as here, they are not.
Upvotes: 2
Reputation: 485
Try using str.format()
for these complicated formatting situations, you can even use triple quoted strings to make it easier.
A = ''' "'{}';'{}'" '''.format(X,Y)
Upvotes: 0