append special chars with "\"

tertius tcronj at
Tue Sep 30 09:46:50 CEST 2003

Is there a better way to append certain chars in a string with a 
backslash that the example below?

chr = "#$%^&_{}"          # special chars to look out for
str = "123 45^ & 00 0_"   # string to convert
n = ""                    # init new string
for i in str:
     if i in chr:          # if special character in str
         n+='\\'           # append it with a backslash
print "old:",str
print "new:",n


More information about the Python-list mailing list