Akshay Hazari
Akshay Hazari

Reputation: 3267

Replace single quote with backslash single quote in python

I have been trying to replace a single quote with back slash single quote.

I have been trying this but it results in a string with two backslashes and single quote or without any backslash and single quote.

re.sub("'","\'","Newton's method")

The above results in O/P : Newton's method

While re.sub("'","\\'","Newton's method") results in Newton\\'s method

I need Newton\'s method as the output.

Any help is appreciated.

Update :

This is a string which is created after parsing and is passed using an html form. Here "Newton's method" causes a problem since it deforms the json after the get request.

{'1': u'Newton metre', '0': u'Newton', '3': u'Newton (unit)', '2': u'Newton Centre, Massachusetts', '5': u'NewtonCotes formulas', '4': u'.30 Newton', '7': u'Newton Highlands, Massachusetts', '6': u"Newton's method", '9': u'List of things named after Isaac Newton', '8': u'Bill Newton'}

The html form gets this by a get request while the back end fetches it incorrectly.

 {'1': u'Newton metre', '0': u'Newton', '3': u'Newton (unit)', '2': u'Newton Centre, Massachusetts', '5': u'NewtonCotes formulas', '4': u'.30 Newton', '7': u'Newton Highlands, Massachusetts', '6': u

Upvotes: 3

Views: 11663

Answers (1)

falsetru
falsetru

Reputation: 368954

You need to escape \ or to use raw string literal:

>>> re.sub("'", "\\'","Newton's method")
"Newton\\'s method"
>>> re.sub("'", r"\'","Newton's method")
"Newton\\'s method"

BTW, for this case, you don't need to use regular expression. str.replace is enough:

>>> "Newton's method".replace(r"'", r"\'")
"Newton\\'s method"

UPDATE

\\ is a way python repr represents backslash chracter in the string. If you print the string, you will see that it's a \.

>>> "Newton\\'s method"
"Newton\\'s method"
>>> print("Newton\\'s method")
Newton\'s method

Upvotes: 2

Related Questions