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?
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
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)
Using String literal concatenation,
print(r"this is '(single quote) and " r'"(double quote)')
# this is '(single quote) and "(double quote)
>>> a=r'''this is '(single quote) and "(double quote)'''
>>> print(a)
this is '(single quote) and "(double quote)