Escape single quote (') in raw string r'…&

2020-07-06 08:49发布

问题:

I want it to print out

this is '(single quote) and "(double quote)

I use the following (I want to use raw string 'r' here)

a=r'this is \'(single quote) and "(double quote)' 

but it prints out

this is \'(single quote) and "(double quote)

What is the correct way to escape ' in raw string?

回答1:

Quoting from Python String Literals Docs,

When an 'r' or 'R' prefix is present, a character following a backslash is included in the string without change, and all backslashes are left in the string. For example, the string literal r"\n" consists of two characters: a backslash and a lowercase 'n'. String quotes can be escaped with a backslash, but the backslash remains in the string; for example, r"\"" is a valid string literal consisting of two characters: a backslash and a double quote.

There are two ways to fixing this

  1. Using multiline raw strings, like mentioned in the section Python Strings

    print(r"""this is '(single quote) and "(double quote)""")
    # this is '(single quote) and "(double quote)
    
  2. Using String literal concatenation,

    print(r"this is '(single quote) and " r'"(double quote)')
    # this is '(single quote) and "(double quote)
    


回答2:

>>> a=r'''this is '(single quote) and "(double quote)'''
>>> print(a)
this is '(single quote) and "(double quote)