Replace all quotes in a string with escaped quotes?

前端 未结 3 1051
遇见更好的自我
遇见更好的自我 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-28 13:22

    Your second attempt is correct, but you're getting confused by the difference between the repr and the str of a string. A more idiomatic way of doing your second way is to use "raw strings":

    >>> s = 'This sentence has some "quotes" in it\n'
    >>> print s
    This sentence has some "quotes" in it
    
    >>> print s.replace('"', r'\"')  # raw string used here
    This sentence has some \"quotes\" in it
    
    >>> s.replace('"', r'\"')
    'This sentence has some \\"quotes\\" in it\n'
    

    Raw strings are WYSIWYG: backslashes in a raw string are just another character. It is - as you've discovered - easy to get confused otherwise ;-)

    Printing the string (the 2nd-last output above) shows that it contains the characters you want now.

    Without print (the last output above), Python implicitly applies repr() to the value before displaying it. The result is a string that would produce the original if Python were to evaluate it. That's why the backlashes are doubled in the last line. They're not in the string, but are needed so that if Python were to evaluate it each \\ would become one \ in the result.

提交回复
热议问题