473,748 Members | 5,230 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 24118
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.u k
int month(char *p){return(1248 64/((p[0]+p[1]-p[2]&0x1f)+1)%12 )["\5\x8\3"
"\6\7\xb\1\x9\x a\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.linu x.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

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

12
28586
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 am testing it now by putting special characters in the description field, this is what I am entering: O'Leary "special edition"
1
1406
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) According to comment # 2, why this special structure for the "for" statement is not working?
0
1985
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 actually part of the file structure anywhere on a disk, but made up by some program? Cheers Greg
1
2020
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 deallocation is necessary. What does the standard say about this? Is this a "feature" I can rely on on
6
1569
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 connections to my database and each connection queries in its own thread as the following: conn1: select fname from root where p_key between 1 and 20000 fname like '%somestring%'; conn2: select fname from root where p_key between 20001 and 40000...
1
2292
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
1620
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 http://www.amazon.com into your web browser, your web browser will change it to http://www.amazon.com/. This is a question of curiosity, like I said, and isn't an ASP.NET question. I simply want to know the reasons why it does this. Thanks!
0
217
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 http://pobox.com/~skeet/csharp/debuggingunicode.html
0
8991
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8830
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9372
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9324
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9247
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6796
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6074
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4606
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4874
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.