473,388 Members | 932 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,388 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 24028
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:35pm, "John Straumann" <jstraum...@hotmail.comwrote: <snip> What's the encoding of the file? That's the first important thing to know. See...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

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.