Python 2 中的以下作品
print ("|").center(11,'-')
当我在 Python 3 中尝试相同的代码时,我收到以下错误消息:
AttributeError: 'NoneType' object has no attribute 'center'
如何在 Python 3 中做同样的事情?
请您参考如下方法:
>>> print("|".center(11, '-'))
-----|-----
在 Python 3 中,print 是一个函数,因此您需要在内部进行居中 - 否则您将在 print 的返回值上调用它。
此外,在 Python 2 中你根本不应该在此处放置括号:
>>> print "|".center(11, '-')
-----|-----
它与括号一起工作的原因是 (foo) 和 foo 是同一件事。
另一种让它在 Python 2 和 Python 3 中工作的选择是将 from __future__ import print_function 添加到文件的顶部,然后使用 Python 3 语法。
