•
•
•
•
What is DaniWeb IT Discussion Community?
You're currently browsing the Python section within the Software Development category of DaniWeb, a massive community of 391,572 software developers, web developers, Internet marketers, and tech gurus who are all enthusiastic about making contacts, networking, and learning from each other. In fact, there are 2,835 IT professionals currently interacting right now! Registration is free, only takes a minute and lets you enjoy all of the interactive features of the site.
Please support our Python advertiser:
Views: 116 | Replies: 3
![]() |
•
•
Join Date: Aug 2008
Posts: 8
Reputation:
Rep Power: 0
Solved Threads: 0
Hello,
Yet another silly question from yours truly. I need to add escape characters to " and ', so that "monkey's cool" becomes \"monkey\'s cool\". My primitive solution to the problem is as follows:
But I bet there is a more efficient and elegant solution to this.
Thank you!
Kind regards,
Dmitri
Yet another silly question from yours truly. I need to add escape characters to " and ', so that "monkey's cool" becomes \"monkey\'s cool\". My primitive solution to the problem is as follows:
str1=raw_input("String:")
str1=str1.replace("\'", "\\\'")
str1=str1.replace("\"", "\\\"")But I bet there is a more efficient and elegant solution to this.
Thank you!
Kind regards,
Dmitri
An extreme solution: a class to escape any set of characters (reuse freely)

The output is
python Syntax (Toggle Plain Text)
#!/usr/bin/env python # escaper.py # a class to escape characters in strings import re class Escaper(object): def __init__(self, chars): self.pat = re.compile("[%s]" % re.escape(chars)) def __call__(self, data): return self.pat.sub(lambda c: "\\"+c.group(0), data) if __name__ == "__main__": esc = Escaper("\"'") esc2 = Escaper("oy ") mystring = '"monkey' + "'s" + ' cool"' print mystring print esc(mystring) print esc2(mystring)

The output is
"monkey's cool" \"monkey\'s cool\" "m\onke\y's\ c\o\ol"
Last edited by Gribouillis : 12 Days Ago at 11:48 am.
![]() |
•
•
•
•
Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
•
•
•
•
•
•
•
•
DaniWeb Python Marketplace
Similar Threads
- unable to open "my computer","control panel". (Viruses, Spyware and other Nasties)
- Matching "pi" but not "pie" (Perl)
- The "gets" command with Borland C++ (C++)
- Convert string "aA" to a BigInteger (Java)
- Removal of "Home Search Assistant", "Search Extender", & "Shopping Wizard" (Viruses, Spyware and other Nasties)
- The question about "new" (C++)
- Transfer from *regular* "phpbb 2.0.11" to "phpbb XTREME 1.7" possible? (Growing an Online Community)
Other Threads in the Python Forum
- Previous Thread: Displaying a raster image from an ESRI .ASC file
- Next Thread: Python challenge help


Linear Mode