我想输出
XYZ's "ABC"
我在 Python IDLE 中尝试了以下 3 个语句。
- 第 1 条和第 2 条语句在
'
之前输出。
- 具有打印功能的第 3 条语句在
'
之前不会输出。
作为 Python 的新手,我想了解为什么在第 1 条和第 2 条语句中'
之前输出。
>>> "XYZ's "ABC""
'XYZ's "ABC"'
>>> "XYZ's "ABC""
'XYZ's "ABC"'
>>> print("XYZ's "ABC"")
XYZ's "ABC"
以下是我在字符串上调用repr()
时的观察: (在 IDLE、REPL 等中也是如此)
如果您打印带有
repr()
的字符串(没有单引号或双引号的普通字符串),则会在其周围添加一个单引号。(注意:当您在 REPL 上按回车键时,repr()
被调用print
而不是由函数调用的__str__
。如果单词有
'
或"
:首先,输出中没有反斜杠。如果单词有'
,输出将被"
包围,如果单词有"
,则'
。如果单词同时具有
'
和"
:输出将被单引号括起来。'
会用反斜杠转义,但"
不会转义。
例子:
def print_it(s):
print(repr(s))
print("-----------------------------------")
print_it('Soroush')
print_it("Soroush")
print_it('Soroush"s book')
print_it("Soroush's book")
print_it('Soroush"s book and Soroush' pen')
print_it("Soroush's book and Soroush" pen")
输出:
'Soroush'
-----------------------------------
'Soroush'
-----------------------------------
'Soroush"s book'
-----------------------------------
"Soroush's book"
-----------------------------------
'Soroush"s book and Soroush' pen'
-----------------------------------
'Soroush's book and Soroush" pen'
-----------------------------------
因此,话虽如此,获得所需输出的唯一方法是在字符串上调用str()
。
- 我知道
Soroush"s book
英语语法不正确。我只想把它放在一个表达式中。
不确定要打印什么。 您希望它输出XYZ's "ABC"
还是XYZ's "ABC"
?
转义下一个特殊字符,如引号,因此如果要打印
代码需要有两个
\
。
string = "Im \"
print(string)
输出:Im
如果要打印引号,则需要单引号:
string = 'theres a "lot of "" in" my "" script'
print(string)
输出:theres a "lot of "" in" my "" script
单引号使您可以在字符串中使用双引号。