关于语法:Python print与single(’)和double(“)引号有什么区别?

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

本问题已经有最佳答案,请猛点这里访问。

这个问题可能很愚蠢。用单引号和双引号在python中打印时在技术上有什么不同吗?

1
2
print '1'
print"1"

它们产生相同的输出。但在口译员级别上必须有所不同。哪种方法是最好的建议?


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

1
2
3
4
print '\'hello\''
print '"hello"'
print""hello""
print"'hello'"

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

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

它是相同的:有关更多信息,请参阅python文档:https://docs.python.org/3/tutorial/introduction.html

1
2
3
4
5
    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:

print函数省略引号:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
    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.
Second line.'
 #
 means newline
>>> s  # without print(),
 is included in the output
'First line.
Second line.'

>>> print(s)  # with print(),
 produces a new line
First line.
Second line.