为什么在 python 中输出这个单引号和大括号?
Why this single quotes and braces in output in python?
我在 ubantu 版本 16.04 中使用 ipython 笔记本并且我 运行 这个代码,
word = 'Rushiraj'
length = 0
for char in 'rushiraj':
length = length + 1
print('There are', length,'character')
我得到这个输出:
('There are', 8, 'character')
输出中出现这个单引号和圆括号是什么原因?不应该出现!
您看到的输出是由于您使用的是 Python 2,但您使用的是 Python 3 中的 print
语法。在 Python 3, print
是一个函数并且像其他函数一样接受参数(如 print(...)
)。
在 Python 2 中,print
是一个语句,通过使用括号,您实际上是将 tuple
作为第一个参数传递给它(因此您正在打印 Python 表示一个元组)。
您可以通过两种方式解决此问题。
如果您将 from __future__ import print_function
添加到文件的顶部,那么 print
的行为将与 Python 中的行为相同 3.
或者,您可以这样称呼它:
print 'There are', length,'character'
您正在打印一个元组(尽管乍一看可能不是那样),因此输出是该元组的 repr。
我在 ubantu 版本 16.04 中使用 ipython 笔记本并且我 运行 这个代码,
word = 'Rushiraj'
length = 0
for char in 'rushiraj':
length = length + 1
print('There are', length,'character')
我得到这个输出: ('There are', 8, 'character')
输出中出现这个单引号和圆括号是什么原因?不应该出现!
您看到的输出是由于您使用的是 Python 2,但您使用的是 Python 3 中的 print
语法。在 Python 3, print
是一个函数并且像其他函数一样接受参数(如 print(...)
)。
在 Python 2 中,print
是一个语句,通过使用括号,您实际上是将 tuple
作为第一个参数传递给它(因此您正在打印 Python 表示一个元组)。
您可以通过两种方式解决此问题。
如果您将 from __future__ import print_function
添加到文件的顶部,那么 print
的行为将与 Python 中的行为相同 3.
或者,您可以这样称呼它:
print 'There are', length,'character'
您正在打印一个元组(尽管乍一看可能不是那样),因此输出是该元组的 repr。