下面是我在字符串上调用repr()
时的观察结果:(在IDLE、REPL等中也是如此)
如果用repr()
打印字符串(没有单引号或双引号的普通字符串),它会在其周围添加single引号.(note:在REPL上按enter键时,repr()
被调用,而不是print
函数调用的__str__
.)
如果单词有either '
或"
:First,则输出中没有反斜杠.如果单词有'
,输出将被"
包围,如果单词有"
,输出将被'
包围.
如果单词有both '
和"
:输出将被single quote包围.'
会用反斜杠逃逸,但"
不会逃逸.
例如:
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
在英语中是语法错误的.我只想把它放在一个表达式中