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

Ken Dyck kd at kendyck.com
Wed Jun 24 12:38:20 EDT 2009


On Jun 24, 12:11 pm, humn <xelothat... at gmail.com> wrote:
> I'm confused as to why this works:
>
> if '\chapter' in line:
>         line = line.replace('\chapter{', '[b][u]')
>         line = line.replace('}', '[/b][/u]')
>
> but this doesn't:
>
> if '\title' in line:
>         line = line.replace('\title{', '[size=150][b]')
>         line = line.replace('}', '[/b][/size]')

In string literals---whether they use single or double quotes---
backslashes are used as escape characters to denote special
characters. The '\t' in '\title' is interpreted as the tab character
so the string that your code is trying to find and replace is actually
'<TAB>itle'. There isn't any special meaning for '\c', so python
interprets that to mean a backslash followed by the character 'c',
which is why the first case works.

There are two ways to solve the problem:

1. Prefix the string literal with an 'r', indicating that backslashes
should not be treated as escape characters (eg. r'\title'), or
2. Use a double backslash in the string literal to indicate that you
mean a literal backslash, not an escape character (eg. '\\title')

The official documentation, including a list of the special escape
sequences, is here:
http://docs.python.org/reference/lexical_analysis.html#string-literals

-Ken



More information about the Python-list mailing list