Skip to main content
 首页 » 编程设计

Python 命令行 "characters"返回 'characters'

2025年05月04日15jillzhang

在此先感谢您的帮助。

在命令行输入“example”时,Python 返回“example”。我在网上找不到任何东西来解释这一点。所有引用资料都在 print 命令的上下文中谈到字符串,我得到了所有关于使用双引号、单引号、三引号、转义命令等的资料。

但是,我找不到任何解释为什么在命令行输入双引号括起来的文本总是返回单引号括起来的相同文本。是什么赋予了?谢谢。

请您参考如下方法:

在 Python 中都是 'string' and "string" are used to represent string literals .它不像 Java,其中单引号和双引号向编译器表示不同的数据类型。

解释器评估您输入的每一行并向您显示该值。在这两种情况下,解释器都会评估您输入的内容、获取字符串并显示该值。显示字符串的默认方式是在单引号中,因此两次显示字符串时都用单引号括起来。

这看起来确实很奇怪 - 因为它打破了 Python 的 There should be one - and preferably only one - obvious way to do it 规则- 但我认为不允许其中一个选项会更糟。

您还可以使用三引号输入字符串文字:

>>> """characters 
... and 
... newlines""" 
'characters\nand\nnewlines' 

你可以使用命令行来确认这些是同一件事:

>>> type("characters") 
<type 'str'> 
>>> type('characters') 
<type 'str'> 
>>> "characters" == 'characters' 
True 

解释器使用 __repr__ method对象的显示以打印给您。因此,在您自己的对象上,您可以确定它们在解释器中的显示方式。我们无法更改内置类型的 __repr__ 方法,但我们可以自定义解释器输出 using sys.displayhook :

>>> import sys 
>>> def customoutput(value): 
...     if isinstance(value,str): 
...        print '"%s"' % value 
...     else: 
...        sys.__displayhook__(value) 
... 
>>> sys.displayhook = customoutput 
>>> 'string' 
"string"