Python打印与单(')和双(")引号有什么区别?

时间:2015-03-07 14:58:04

标签: python syntax

这个问题可能非常愚蠢。使用单引号和双引号在Python中打印时,技术上是否存在任何差异。

print '1'
print "1"

它们产生相同的输出。但是在翻译层面必须有所不同。哪个是最好的建议方法?

2 个答案:

答案 0 :(得分:1)

它是相同的:有关更多信息,请参阅Python文档: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:

打印功能省略了引号:

    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.

答案 1 :(得分:1)

当使用带有单引号括起来的字符串的print函数时,单引号需要转义字符,但双引号不需要;对于用双引号括起来的字符串,双引号需要转义字符,但单引号不需要:

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

如果要同时使用单引号和双引号而不必担心转义字符,可以使用三个双引号或三个单引号打开和关闭字符串:

print """In this string, 'I' can "use" either."""
print '''Same 'with' "this" string!'''