473,324 Members | 2,501 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,324 software developers and data experts.

append special chars with "\"

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
14 24016
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
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
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
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
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
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
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

"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
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
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
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
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
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
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

12
by: Mosher | last post by:
Hi all, I have an issue with php and/or mysql. I have a php form that writes "items" to a mysql database, including a description of the item. On the mysql server, "magic_quotes_gpc" is ON. I...
1
by: knocte | last post by:
Hello group. In the following testcase I attach to the final of the message, I have two questions: 1) According to comment # 1, how can I pass an argument to the function that way? 2)...
0
by: Greg Bacchus | last post by:
Hi, Does anyone know how to make "special" folder apear under "My Computer". Like the Control Panel, or when a Camera appears when plugged in. And have it so that the contents of that folder is not...
1
by: vl106 | last post by:
char* foo () { return "abc"; } I compiled the above code both with MSVC and GCC for PPC. The string "abc" is generated as a global entity. Thus (1) foo doesn't return a temporary and (2) no...
6
by: Christian Maier | last post by:
Hello! I have huge unperformant "where like" querys to a mysql DB. So there are some performance issues. To resolve my performance problem I thougt to split the query into threads. I hold 10...
1
by: ofir | last post by:
I don't understand. according to MSDN session id sould be LONG but when I look at the value of Context.Session.SessionID in my asp.net application I get a 24 chars value
1
by: =?Utf-8?B?TWlrZQ==?= | last post by:
This question isn't a true ASP.NET-related question, but I don't know where else to post it. Why do web browsers automatically append URL's with a forward-slash (/)? For example, if you type...
0
by: Jon Skeet [C# MVP] | last post by:
On Sep 30, 12:35 pm, "John Straumann" <jstraum...@hotmail.comwrote: <snip> What's the encoding of the file? That's the first important thing to know. See...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.