Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escape single quote (') in raw string r'...'

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?

like image 581
william007 Avatar asked Dec 14 '14 09:12

william007


2 Answers

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)
    
like image 173
thefourtheye Avatar answered Sep 19 '22 05:09

thefourtheye


>>> a=r'''this is '(single quote) and "(double quote)'''
>>> print(a)
this is '(single quote) and "(double quote)
like image 41
jamylak Avatar answered Sep 23 '22 05:09

jamylak