Python 3 相当于 Python 2 中心

标签 python

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 语法。

关于Python 3 相当于 Python 2 中心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36179327/

相关文章:

python - ember-django-adapter 代码示例

python - 在 pyspark Dataframe 中找到 10,000 列的均值和校正

python - 如何在急切执行中暂停和恢复渐变录音?

python - 如何使用虚拟环境在ansible playbook中运行python脚本?

python - 每个时期的数据大小都不同

Python:list() 函数搞乱了 map()

python - 为什么 Python 的 filter(predicate, set) 不返回一个集合?

python - "File not found"tkinter 按钮命令出错

python - 获取 NxN 网格 python 的邻居

python - 使用细化和命中或遗失实现的骨架化永不停止