append special chars with "\"

T

tertius

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
 
A

Alex Martelli

tertius said:
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
 
D

Duncan Booth

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\_
 
T

Tertius

Alex said:
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!
 
G

Gerrit Holl

tertius said:
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.
 
C

Christos TZOTZIOY Georgiou

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'...
 
A

Alex Martelli

Christos said:
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
 
T

Terry Reedy

tertius said:
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
 
C

Christos TZOTZIOY Georgiou

Christos said:
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 :)
 
B

Bengt Richter

[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
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 ;-)
... (lambda d,c: d.get(c,c)).__get__(
... dict([(c,'\\'+c) for c in '#$%^&_{}']))) <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:
... return (lambda f,s: ''.join(map(f,s))).__get__(
... (lambda d,c: d.get(c,c)).__get__(
... dict([(c,'\\'+c) for c in escaped])))
... \12\3 4\5^ \& 00 0_

Now Alex can <nit> me back ;-)

Regards,
Bengt Richter
 
P

Peter Hansen

Alex said:
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
 
T

Tertius Cronje

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
 
T

tertius

tertius said:
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!!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,164
Messages
2,570,898
Members
47,440
Latest member
YoungBorel

Latest Threads

Top