关于格式字符串的简单python混淆

2024-04-19 21:03:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python新手,正在学习本教程: http://learnpythonthehardway.org/book/ex8.html

我就是不明白为什么“但它不唱”这句话是用双引号打印出来的,而其他的都是用单引号打印出来的。。看不出代码有什么不同。。。你知道吗


Tags: 代码orghttphtml教程新手book双引号
3条回答

值的表示应该与生成它所需的Python代码等效。由于字符串“But it didn't sing.”包含单引号,因此使用单引号对其进行分隔将创建无效代码。因此使用双引号代替。你知道吗

引号取决于字符串:如果没有引号,则使用简单引号:

>>> """no quotes"""
'no quotes'

如果有单引号,则使用双引号:

>>> """single quote:'"""
"single quote:'"

如果有双引号,它将使用单引号:

"""double quote:" """ 'double quote:" '

如果两者都有,它将使用单引号,从而转义单引号:

>>> """mix quotes:'" """
'mix quotes:\'" '
>>> """mix quotes:"' """
'mix quotes:"\' '
>>> '''mix quotes:"' '''
'mix quotes:"\' '

但打印字符串时不会有任何区别:

>>> print '''mix quotes:"' '''
mix quotes:"'

引号用于表示字符串:

>>> print str('''mix quotes:"' ''')
mix quotes:"'
>>> print repr('''mix quotes:"' ''')
'mix quotes:"\' '

您可能需要检查字符串上的pythontutorial。你知道吗

Python有几个输出repr字符串的规则。你知道吗

通常,它使用'来包围它们,除非其中有',然后它使用"来消除引用的需要。你知道吗

如果字符串同时包含'和“characters, it usess and quotes the”`。你知道吗

由于一个字符串可以有几个有效的和等价的表示形式,这些rue可能会随着版本的不同而变化。你知道吗

顺便说一句,在你链接到的网站上,答案也给出了:

Q: Why does %r sometimes print things with single-quotes when I wrote them with double-quotes?

A: Python is going to print the strings in the most efficient way it can, not replicate exactly the way you wrote them. This is perfectly fine since %r is used for debugging and inspection, so it's not necessary that it be pretty.

相关问题 更多 >