Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Having both single and double quotation in a Python string

Tags:

python

string

I'm trying to have a string that contains both single and double quotation in Python (' and "). However, Python always automatically corrects this to (\', "). I wonder if there's a way to put a double quotation and a single quotation together as it is.

like image 799
GHO Avatar asked Sep 20 '11 14:09

GHO


People also ask

How do you print double and single quotes in Python?

If you want to use both single- and double-quotes without worrying about escape characters, you can open and close the string with three double-quotes or three single-quotes: print """In this string, 'I' can "use" either. """ print '''Same 'with' "this" string!

Does Python Use single or double quotes for strings?

When programming with Python, we generally use single quotes for string literals. For example – 'my-identifier'. Let us understand with an example through code in Python. NOTE: Always make use of single quotes when you know your string may contain double quotes within.

How do you escape single and double quotes in Python?

You can put a backslash character followed by a quote ( \" or \' ). This is called an escape sequence and Python will remove the backslash, and put just the quote in the string. Here is an example. The backslashes protect the quotes, but are not printed.

How do you enclose a string in Python with double quotes?

Quotes in strings are handled differently There is no problem if you write \" for double quotes " . 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 \" .


2 Answers

Use triple quotes.

"""Trip'le qu"oted""" 

or

'''Ag'ain qu"oted''' 

Keep in mind that just because Python reprs a string with backslashes, doesn't mean it's actually added any slashes to the string, it may just be showing special characters escaped.

Using an example from the Python tutorial:

>>> len('"Isn\'t," she said.') 18 >>> len('''"Isn't," she said.''') 18 

Even though the second string appears one character shorter because it doesn't have a backslash in it, it's actually the same length -- the backslash is just to escape the single quote in the single quoted string.

Another example:

>>> for c in '''"Isn't," she said.''': ...     sys.stdout.write(c) ...  "Isn't," she said. >>>  

If you don't let Python format the string, you can see the string hasn't been changed, it was just Python trying to display it unambiguously.

See the tutorial section on strings.

like image 77
agf Avatar answered Sep 21 '22 17:09

agf


Use triple-quoted strings:

""" This 'string' contains "both" types of quote """ ''' So ' does " this ''' 
like image 37
multipleinterfaces Avatar answered Sep 22 '22 17:09

multipleinterfaces