How to include a quote in a raw Python string
Consider:
>>> r"what"ever"
SyntaxError: invalid syntax
>>> r"what\"ever"
'what\\"ever'
So how do we get the quote, but not the slash?
And please don't suggest r'what"ever'
, because then the question just becomes how do we include both types of quotes?
Related
Solution 1:
If you want to use double quotes in strings but not single quotes, you can just use single quotes as the delimiter instead:
r'what"ever'
If you need both kinds of quotes in your string, use a triple-quoted string:
r"""what"ev'er"""
If you want to include both kinds of triple-quoted strings in your string (an extremely unlikely case), you can't do it, and you'll have to use non-raw strings with escapes.
Solution 2:
If you need any type of quoting (single, double, and triple for both) you can "combine"(0) the strings:
>>> raw_string_with_quotes = r'double"' r"single'" r'''double triple""" ''' r"""single triple''' """
>>> print raw_string_with_quotes
double"single'double triple""" single triple'''
You may also "combine"(0) raw strings with non-raw strings:
>>> r'raw_string\n' 'non-raw string\n'
'raw_string\\nnon-raw string\n'
(0): In fact, the Python parser joins the strings, and it does not create multiple strings. If you add the "+" operator, then multiple strings are created and combined.
Solution 3:
Python has more than one way to do strings. The following string syntax would allow you to use double quotes:
'''what"ever'''