Wow, this should be so simple, but it\' just not working. I need to inset a \"\\\" into a string (for a Bash command), but escaping just doesn\'t work.
>>&
'tes\\ting'
is correct, but you are viewing the repr
output for the string, which will always show escape characters.
>>> print 'tes\\ting'
tes\ting
You are being misled by Python's output. Try:
>>> a = "test\\ing"
>>> print(a)
test\ing
>>> print(repr(a))
'test\\ing'
>>> a
'test\\ing'
If you want double slashes because the shell will escape \ again, use a raw string:
b = a[:3] + r'\\' + a[3:]
The second example is correct. There are two slashes because you are printing the Python representation of the string.
If you want to see the actual string, call print a
.
b is fine in the second example, you see two slashes because you're printing the representation of b, so slashes are escaped in it too.
>>> b
'tes\\ting'
>>> print b
tes\ting
>>>
Python's quoting the backslash again when it shows you the representation of the string (in such a way that you could paste it in and get the string with an escaped backslash).
If you print the string, you'll see there's only one in the actual string.
>>> print "hello\\world"
hello\world