append special chars with "\"

tertius tcronj at ananzi.co.za
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
     n+=i
print "old:",str
print "new:",n


Thanks
Tertius





More information about the Python-list mailing list