append special chars with "\"

Terry Reedy tjreedy at
Tue Sep 30 16:51:19 CEST 2003

"tertius" <tcronj at> wrote in message
news:3f793544$0$64721 at
> 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

You are pre-pending '\' (putting it before), which is probably what
you want to do, not ap-pending (putting it after).  In Alex's answer,
he actually did append, as claimed you were doing, but which is
probably not what you want.  If indeed not, you will want to change
c+'\\' to '\\'+c

Terry J. Reedy

More information about the Python-list mailing list