Escaping the semicolon?

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Tue Dec 4 11:02:03 EST 2007


Nick a écrit :
> Hi all,
> 
> Is this expected behavior?
> 
>>>> s = '123;abc'
>>>> s.replace(';', '\;')
> '123\\;abc'

 >>> print s.replace(';', '\;')
123\;abc

> I just wanted a single backslash.

You got it - even if it's not obvious !-)

> I can see why this probably happens
> but i wondered if it is definitely intentional.

 >>> s2 = '123\;abc'
 >>> s2
'123\\;abc'
 >>> print s2
123\;abc
 >>> list(s2)
['1', '2', '3', '\\', ';', 'a', 'b', 'c']

As you can see, '\\' is counted as a single character !-)
Since the backslash is the escape character, you need to escape it to 
have a litteral backslash:

 >>> s3 = '\'
   File "<stdin>", line 1
     s3 = '\'
            ^
SyntaxError: EOL while scanning single-quoted string
 >>>



More information about the Python-list mailing list