By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,758 Members | 1,223 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,758 IT Pros & Developers. It's quick & easy.

append special chars with "\"

P: n/a
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

Jul 18 '05 #1
Share this Question
Share on Google+
14 Replies


P: n/a
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

Jul 18 '05 #2

P: n/a
tertius <tc****@ananzi.co.za> wrote in
news:3f**************@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 du****@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?
Jul 18 '05 #3

P: n/a
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!
Jul 18 '05 #4

P: n/a
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


Another possibility:

for c in chr:
str = str.replace(c, r"\c")

Untested, however, but something like this should work.

Gerrit.

--
1. If any one ensnare another, putting a ban upon him, but he can not
prove it, then he that ensnared him shall be put to death.
-- 1780 BC, Hammurabi, Code of Law
--
Asperger Syndroom - een persoonlijke benadering:
http://people.nl.linux.org/~gerrit/
Het zijn tijden om je zelf met politiek te bemoeien:
http://www.sp.nl/

Jul 18 '05 #5

P: n/a
On Tue, 30 Sep 2003 07:58:27 GMT, rumours say that Alex Martelli
<al***@aleax.it> might have written:
charmap = {}
for c in chr: charmap[c] = c+'\\'


I believe you meant charmap[c] = '\\' + c ...
--
TZOTZIOY, I speak England very best,
Ils sont fous ces Redmontains! --Harddix
Jul 18 '05 #6

P: n/a
On Tue, 30 Sep 2003 13:33:31 +0200, rumours say that Gerrit Holl
<ge****@nl.linux.org> might have written:
for c in chr:
str = str.replace(c, r"\c")


Perhaps you meant:

for c in chr:
str = str.replace(c, r"\%s" % c)

otherwise all characters in chr would change into a literal
'backslash-c'...
--
TZOTZIOY, I speak England very best,
Ils sont fous ces Redmontains! --Harddix
Jul 18 '05 #7

P: n/a
Christos TZOTZIOY Georgiou wrote:
On Tue, 30 Sep 2003 07:58:27 GMT, rumours say that Alex Martelli
<al***@aleax.it> might have written:
charmap = {}
for c in chr: charmap[c] = c+'\\'


I believe you meant charmap[c] = '\\' + c ...


Sure, if the original poster wants the backslash BEFORE the character
(the "append" in the subject suggested to me he wanted it AFTER).
Alex

Jul 18 '05 #8

P: n/a

"tertius" <tc****@ananzi.co.za> wrote in message
news:3f**************@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


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
Jul 18 '05 #9

P: n/a
On Tue, 30 Sep 2003 14:50:19 GMT, rumours say that Alex Martelli
<al***@aleax.it> might have written:
Christos TZOTZIOY Georgiou wrote:
On Tue, 30 Sep 2003 07:58:27 GMT, rumours say that Alex Martelli
<al***@aleax.it> might have written:
charmap = {}
for c in chr: charmap[c] = c+'\\'


I believe you meant charmap[c] = '\\' + c ...


Sure, if the original poster wants the backslash BEFORE the character
(the "append" in the subject suggested to me he wanted it AFTER).


You are correct about the subject (append instead of 'pre-pend' -sp?),
but the OP's code was not appending, in spite of the comments:

for i in str:
if i in chr: # if special character in str
n+='\\' # append it with a backslash
n+=i

I just assumed the OP was a better coder than English speaker :)
--
TZOTZIOY, I speak England very best,
Ils sont fous ces Redmontains! --Harddix
Jul 18 '05 #10

P: n/a
Isn't this what re.escape(string) is for?

"tertius" <tc****@ananzi.co.za> wrote in message
news:3f**************@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
Thanks
Tertius

Jul 18 '05 #11

P: n/a
On Tue, 30 Sep 2003 10:36:48 +0200, Tertius <tc****@ananzi.co.za> wrote:
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 <nit1 kind="builtin-shadowing-abuse"/>str = "123 45^ & 00 0_" # string to convert <nit2 kind="builtin-shadowing-abuse"/>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 [Note that n+=i comes _after_ n+='\\' -- cf nit3]
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+'\\' <nit 3>
for c in chr: charmap[c] = '\\'+c
</nit3>

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!


Re nits: Alex must have been doing this while talking on the 'phone and playing bridge
or I think he would have mentioned that using builtin names (e.g., chr & str) for your
variables is a bad idea. I think your comment "append _it_ with a backslash" was misleading,
since the "it" was not the character, but the accumulating output.

If you want to play, you can also define a translation function like the following ;-)
trans = (lambda f,s: ''.join(map(f,s))).__get__( ... (lambda d,c: d.get(c,c)).__get__(
... dict([(c,'\\'+c) for c in '#$%^&_{}']))) print trans("123 45^ & 00 0_") 123 45\^ \& 00 0\_ trans <bound method ?.<lambda> of <bound method ?.<lambda> of {'#': '\\#', '%': '\\%', '$': '\\$', '&'
: '\\&', '{': '\\{', '}': '\\}', '_': '\\_', '^': '\\^'}>>

(I think all the work is done up front ;-)

This form is obviously easy to parameterize as to which characters you want escaped, BTW:
def maketrans(escaped='#$%^&_{}'): ... return (lambda f,s: ''.join(map(f,s))).__get__(
... (lambda d,c: d.get(c,c)).__get__(
... dict([(c,'\\'+c) for c in escaped])))
... trans = maketrans()
print trans("123 45^ & 00 0_") 123 45\^ \& 00 0\_ trans = maketrans('135&')
print trans("123 45^ & 00 0_")

\12\3 4\5^ \& 00 0_

Now Alex can <nit> me back ;-)

Regards,
Bengt Richter
Jul 18 '05 #12

P: n/a
Alex Martelli wrote:

Christos TZOTZIOY Georgiou wrote:
On Tue, 30 Sep 2003 07:58:27 GMT, rumours say that Alex Martelli
<al***@aleax.it> might have written:
charmap = {}
for c in chr: charmap[c] = c+'\\'


I believe you meant charmap[c] = '\\' + c ...


Sure, if the original poster wants the backslash BEFORE the character
(the "append" in the subject suggested to me he wanted it AFTER).


Even many native English speakers unfortunately seem to think that
"append" means merely "attach". "Prepend" sounds to them as a foreign
word... only context can resolve the resulting problem.

-Peter
Jul 18 '05 #13

P: n/a
Gerrit Holl wrote:


tertius wrote:



Is there a better way to append certain chars in a string with a backslash that the example below? chr = "#$%^&amp;_{}" # special chars to look out for str = "123 45^ &amp; 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



Another possibility: for c in chr: str = str.replace(c, r"\c") Untested, however, but something like this should work. Gerrit.

Nope, but&nbsp; *"\\"+c*&nbsp; does the trick !

Thanks for this simplistic solution :)

Tertius

Jul 18 '05 #14

P: n/a
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
Thanks
Tertius

I meant *pre*-pend... but the msg got accross.

Thanks all!!

Jul 18 '05 #15

This discussion thread is closed

Replies have been disabled for this discussion.