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:

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

3
Contributors
3
Replies
4
Views
9 Years
Discussion Span
Last Post by dmpop
0

An extreme solution: a class to escape any set of characters (reuse freely)

#!/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"
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.