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

2009-06-24 Thread humn
I'm writing a script to convert Latex commands to bbcode by using the
str.replace function and 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]')

Here is the short version of the script:

infile = open('test.tex')

outfilename = infile.name.partition('.')[0] + '.bbcode'
outfile = open(outfilename, 'w')

for line in infile:

if '\title' in line:
line = line.replace('\title{', '[size=150][b]')
line = line.replace('}', '[/b][/size]\n')

if '\chapter' in line:
line = line.replace('\chapter{', '[b][u]')
line = line.replace('}', '[/u][/b]')

outfile.write(line)

infile.close()
outfile.close()
-- 
http://mail.python.org/mailman/listinfo/python-list


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

2009-06-24 Thread humn
On Jun 24, 12:28 pm, unayok  wrote:
> On Jun 24, 12:11 pm, humn  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  character. so, '\title' will look for
> '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.
-- 
http://mail.python.org/mailman/listinfo/python-list