views:

67

answers:

2

I need to replace some characters as follows : & -> \&, # -> \#, ...

I coded as follows, but I guess there should be a much better way. Any hints?

strs = strs.replace('&', '\&')
strs = strs.replace('#', '\#')
...
A: 

Are you always going to prepend a backslash? If so, try

import re
rx = re.compile('([&#])')
#                  ^^ fill in the characters here.
strs = rx.sub('\\\\\\1', strs)

It may not be the most efficient method but I think it is the easiest.

KennyTM
A: 
>>> string="abc&def#ghi"
>>> for ch in ['&','#']:
...   if ch in string:
...      string=string.replace(ch,"\\"+ch)
...
>>> print string
abc\&def\#ghi
ghostdog74