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

4
这个问题可能很幼稚。在Python中,使用单引号和双引号打印有技术上的区别吗?
print '1'
print "1"

它们产生相同的输出。但在解释器层面上必须有区别。哪种方法是最佳建议?


没有区别。最好的是你喜欢的,所以完全取决于个人偏好。 - undefined
通常我更喜欢使用单引号,因为这样可以少按一个键,不需要按住Shift键。 - undefined
2个回答

4

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

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

如果你想同时使用单引号和双引号而不必担心转义字符,你可以用三个单引号或三个双引号来打开和关闭字符串:
print """In this string, 'I' can "use" either."""
print '''Same 'with' "this" string!'''

2

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接