What is the difference in Python print with single (') and double (") quotation marks?

10,822

Solution 1

When using the print function with a string enclosed in single-quotes, a single-quote requires an escape character, but a double-quote does not; for a string enclosed in double-quotes, a double-quote requires an escape character, but a single-quote does not:

print '\'hello\''
print '"hello"'
print "\"hello\""
print "'hello'"

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!'''

Solution 2

It is the same: See the Python documentation for more information: https://docs.python.org/3/tutorial/introduction.html

    3.1.2. Strings
    Besides numbers, Python can also manipulate strings, 
which can be expressed in several ways. 
They can be enclosed in single quotes ('...') or double quotes ("...") 
with the same result [2]. \ can be used to escape quotes:

The print function omits the quotes:

    In the interactive interpreter, the output string is enclosed in quotes and special characters are escaped with backslashes. 
While this might sometimes look different from the input (the enclosing quotes could change), the two strings are equivalent. 
The string is enclosed in double quotes if the string contains a single quote and no double quotes, otherwise it is enclosed in single quotes. 
The print() function produces a more readable output, by omitting the enclosing quotes and by printing escaped and special characters

>>> '"Isn\'t," she said.'
'"Isn\'t," she said.'
>>> print('"Isn\'t," she said.')
"Isn't," she said.
>>> s = 'First line.\nSecond line.'  # \n means newline
>>> s  # without print(), \n is included in the output
'First line.\nSecond line.'
>>> print(s)  # with print(), \n produces a new line
First line.
Second line.
Share:
10,822
Tom Kurushingal
Author by

Tom Kurushingal

Updated on June 04, 2022

Comments

  • Tom Kurushingal
    Tom Kurushingal almost 2 years

    This question might be a very silly one. Is there technically any difference when printing in Python using single and double quotation marks.

    print '1'
    print "1"
    

    They produce the same output. But there has to be a difference at the interpreter level. And which is the best suggested method?