Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include a quote in a raw Python string

Tags:

python

syntax

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

like image 349
mpen Avatar asked Jan 07 '11 21:01

mpen


People also ask

How do you put a quote inside a string?

To place quotation marks in a string in your code In Visual Basic, insert two quotation marks in a row as an embedded quotation mark. In Visual C# and Visual C++, insert the escape sequence \" as an embedded quotation mark.

How do you code quotes in Python?

Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals, as long as the same type of quote starts and ends the string. word = 'word' sentence = "This is a sentence." paragraph = """This is a paragraph. It is made up of multiple lines and sentences."""

How do I put double quotes in a string in Python?

Quotes in strings are handled differently In a string enclosed in double quotes " , single quotes ' can be used as is, but double quotes " must be escaped with a backslash and written as \" .


1 Answers

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.

like image 125
Adam Rosenfield Avatar answered Oct 03 '22 12:10

Adam Rosenfield