How do I escape backslash and single quote or double quote in Python?

前端 未结 5 1320
甜味超标
甜味超标 2020-12-06 19:57

How do I escape a backslash and a single quote or double quote in Python?

For example:

Long string = \'\'\'some \'long\' string \\\' and \\\" some \'         


        
5条回答
  •  佛祖请我去吃肉
    2020-12-06 20:38

    The problem is that in your string \' and \" get converted to ' and ", so on your example as-is, you won't be able to match only \' without matching the single quotes around long.

    But my understanding is that this data comes from a file so assuming you have your_file.txt containing

    some 'long' string \' and \" some 'escaped' strings
    

    you can replace \' and \" with following code:

    import re
    
    from_file = open("your_file.txt", "r").read()
    
    print(re.sub("\\\\(\"|')", "thevalue", from_file))
    

    Note the four slashes. Since this is a string \ gets converted to \ (as this is an escaped character). Then in the regular expression, the remaining \ gets again converted to \, as this is also regular experssion escaped character. Result will match a single slash and one of the " and ' quotes.

提交回复
热议问题