在 python 解释器中,为什么使用显式 "print" 和不使用它的结果不同?

In python interpreters, why are results different between using an explicit "print" and not using it?

>>> 'sp\xc4m'
'sp\xc4m'
>>> print('sp\xc4m')
spÄm

(screenshot)

在IDLE中,我认为使用函数"print"和不使用它应该是一样的。而这本书"Learning Python(5th)"支持我的观点

>>> lumberjack = 'okay'
>>> lumberjack
'okay'

example from book

我是大一学生python,我的母语不是英语,所以可能我的问题和表情很有趣,但我一直在学习。谢谢你的帮助。

IDLE 打印字符串(或其他任何内容)的 repr

>>> print 'sp\xc4m'
sp?m
>>> 'sp\xc4m'
'sp\xc4m'
>>> print repr('sp\xc4m')
'sp\xc4m'
>>> 

交互式解释器的自动打印行为等同于

_ = the_expression_you_typed
if _ is not None:
    print repr(_)

除了 None 之外,这与 print _ 的不同之处在于 print _ 会调用 str 而不是 repr。从表面上看,strrepr 之间的区别在于 str 应该产生更多人类可读的输出,而 repr 应该产生明确的东西,理想情况下是一段生成对象的源代码。

Really, though, the main reason the two functions exist is so print "asdf" prints asdf and just typing "asdf" prints "asdf".

IDLE 中的交互式解释器有助于调试。如果我写:

>>> print s
a       b

变量s中实际包含了什么?您可以查看:

>>> s
'a\tb'

现在你可以看到它是三个字符,a,一个显示为转义序列的制表符\t,和b。它可能是 'a b'(九个带空格的字符)或 `'a b '(十二个带尾随空格的字符)。两者的打印方式相同,但调试表示通过转义码和引用字符串以可视化起点和终点来帮助确定确切内容。

这叫做变量的"representation",是一个可以被函数repr()访问的调试值。 IDLE 使用它来显示未显式打印的变量。

在交互式提示中,显示一个没有print的变量是为了调试。不在脚本中使用 print 将不会显示任何内容。要在脚本中强制显示调试值,请使用 print repr(s).