Replace all quotes in a string with escaped quotes?

前端 未结 3 1058
遇见更好的自我
遇见更好的自我 2020-12-28 12:36

Given a string in python, such as:

s = \'This sentence has some \"quotes\" in it\\n\'

I want to create a new copy of that string with any q

3条回答
  •  半阙折子戏
    2020-12-28 13:09

    Your last attempt was working as you expected it to. The double backslashes you see are simply a way of displaying the single backslashes that are actually in the string. You can verify this by checking the length of the result with len().

    For details on the double backslash thing, see: __repr__()


    UPDATE:

    In response to your edited question, how about one of these?

    print repr(s).replace('"', '\\"')
    print s.encode('string-escape').replace('"', '\\"')
    

    Or for python 3:

    print(s.encode('unicode-escape').replace(b'"', b'\\"'))
    

提交回复
热议问题