这个问题可能很幼稚。在Python中,使用单引号和双引号打印有技术上的区别吗?
print '1'
print "1"
它们产生相同的输出。但在解释器层面上必须有区别。哪种方法是最佳建议?
使用带有单引号括起来的字符串时,print
函数需要一个转义字符来处理单引号,但是不需要处理双引号;对于用双引号括起来的字符串,print
函数需要一个转义字符来处理双引号,但是不需要处理单引号:
print '\'hello\''
print '"hello"'
print "\"hello\""
print "'hello'"
print """In this string, 'I' can "use" either."""
print '''Same 'with' "this" string!'''
它是相同的:有关更多信息,请参阅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.