append special chars with "\"

Tertius tcronj at ananzi.co.za
Tue Sep 30 04:36:48 EDT 2003


Alex Martelli wrote:
> tertius wrote:
> 
> 
>>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
> 
> 
> If you can afford some a priori preparation, make a dictionary
> once and for all that maps each character (that isn't to be
> represented by itself) to the string that represents it.  E.g.,
> if you inevitably start with a chr string as above, you can
> make the dictionary as follows:
> 
> charmap = {}
> for c in chr: charmap[c] = c+'\\'
> 
> You can also write out the dict literal directly, and in
> any case you only need to prepare this charmap once and
> can then use it to prepare any number of translations.
> 
> Once you have this charmap, you can use its get method to
> get the translations -- and prepare a *LIST OF STRINGS* to
> be joined up at the end, that's MUCH, *MUCH* faster than
> a loop using += on a string:
> 
> pieces = [charmap.get(c,c) for c in str]
> 
> and finally:
> 
> n = ''.join(pieces)
> 
> 
> Alex
> 

*MUCH* nicer :)
Thanks!






More information about the Python-list mailing list