fandingo
fandingo

Reputation: 1360

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'
>>> b = a[:3] + '\' + a[3:]
    >>> File "<stdin>", line 1
    >>> b = a[:3] + '\' + a[3:]
                              ^
   >>>SyntaxError: EOL while scanning string literal
>>> b = a[:3] + '\\' + a[3:]
>>> b
'tes\\ting'
>>> sys.version
'2.7 (r27:82500, Sep 16 2010, 18:02:00) \n[GCC 4.5.1 20100907 (Red Hat 4.5.1-3)]' 

The first error is understandable and expexted. The end quote is being eaten, and the interpreter barfs. However, the second example should work. Why is there two slashes?

Python 2.7

Thanks,

Edit: Thanks Greg. It was a problem with working at the interpreter and not using repr(b). Python was working correctly, but I wasn't looking at the correct version of the output.

Upvotes: 1

Views: 440

Answers (6)

hbn
hbn

Reputation: 1946

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

Upvotes: 0

Paulo Scardine
Paulo Scardine

Reputation: 77251

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

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

Upvotes: 1

Emile
Emile

Reputation: 2971

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

Upvotes: 0

Nate
Nate

Reputation: 19030

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.

Upvotes: 1

Ben James
Ben James

Reputation: 125157

'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

Upvotes: 1

Greg Hewgill
Greg Hewgill

Reputation: 993095

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

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

Upvotes: 7

Related Questions