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

That seems concise and simple to me.

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"

Thanks, guys!

Kind regards,
Dmitri

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.