regex - How to replace single qoute to backslash+single qoute in Python -


need replace ' \' get:

>>> s = "it's nice have example" >>> s.replace("'", "\\'") "it\\'s nice have example" >>> s.replace("'", "\'") "it's nice have example" >>> s.replace("'", "\\\'") "it\\'s nice have example" 

how "it\'s nice have example" result?

you got right, representation of string threw off. try:

print s.replace("'", "\\'") =>  it\'s nice have example 

if don't use print, repr of resulting string displayed (and not str), , in repr, backslashes escaped, resulting double-backslash.

see this question, __str__ , __repr__.


edit -- since mentioned in comment need string can use in javascript...

use json.dumps(), instead of repr.


Comments

Popular posts from this blog

php - SPIP: From Tag directly to an article -

jquery - isAjaxRequest always return false -

ruby on rails - In a controller spec, how to find a specific tag in the generated view? -