Skip to content Skip to sidebar Skip to footer

Escape For Str In Python

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. >>> a = 'testing' >&g

Solution 1:

You are being misled by Python's output. Try:

>>>a = "test\\ing">>>print(a)
test\ing
>>>print(repr(a))
'test\\ing'
>>>a
'test\\ing'

Solution 2:

'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

Solution 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.

Solution 4:

If you want double slashes because the shell will escape \ again, use a raw string:

b = a[:3] + r'\\' + a[3:]

Solution 5:

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
>>>

Post a Comment for "Escape For Str In Python"