Why is it that str.replace doesn't work sometimes?

MRAB python at mrabarnett.plus.com
Wed Jun 24 12:58:48 EDT 2009


humn wrote:
> On Jun 24, 12:28 pm, unayok <una... at gmail.com> wrote:
>> On Jun 24, 12:11 pm, humn <xelothat... at gmail.com> wrote:
>>
>>> but this doesn't:
>>> if '\title' in line:
>>>         line = line.replace('\title{', '[size=150][b]')
>>>         line = line.replace('}', '[/b][/size]')
>> \t is an escaped <tab> character. so, '\title' will look for
>> '<tab>itle'
>>
>> Two ways to fix this:
>>
>> 1. use r'\title'
>>
>> 2. use '\\title'
>>
>> \c does not represent a known escape sequence so it remains two
>> characters.
> 
> Thank you! Didn't know that it would escape characters with single
> quotes. I thought it only did that with double quotes.

There's no difference between the two types of quote character. Python
itself prefers to show ' when printing, unless " would be clearer:

 >>> # The empty string.
 >>> ''
''
 >>> ""
''
 >>> # Quoting the other type.
 >>> '"'
'"'
 >>> "'"
"'"
 >>> # Quoting the same type.
 >>> '\''
"'"
 >>> "\""
'"'



More information about the Python-list mailing list