append special chars with "\"
Duncan Booth
duncan at NOSPAMrcp.co.uk
Tue Sep 30 04:26:03 EDT 2003
tertius <tcronj at ananzi.co.za> wrote in
news:3f793544$0$64721 at hades.is.co.za:
> 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
>
Not using builtins as variable names would be better for a start. 'chr' is
a builtin function, 'str' is a builtin type.
Building a string by appending characters is never a good idea, if you try
this code with longer strings you will rapidly find it grinds to a halt.
The Pythonic way to build up a string from substrings is either to use
str.join on a list of strings, or to use StringIO.
Regular expressions are rarely the best solution to a problem, but in this
case it seems they could be:
>>> import re
>>> myStr = "123 45^ & 00 0_"
>>> print re.sub("([#$%^&_{}])", r"\\\1", myStr)
123 45\^ \& 00 0\_
The only real catch is that if your list of special characters is variable
and sometimes contains ']' you have a bit of work to build the regular
expression.
A solution without regular expressions (so it works for any string of
special characters) would be:
>>> specialChars = "#$%^&_{}"
>>> myStr = "123 45^ & 00 0_"
>>> specials = dict([(c, '\\'+c) for c in specialChars])
>>> print str.join('', [ specials.get(c, c) for c in myStr ])
123 45\^ \& 00 0\_
--
Duncan Booth duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?
More information about the Python-list
mailing list