简体   繁体   English

相当于Python 2中心的Python 3

[英]Python 3 equivalent of Python 2 center

The following Works in Python 2 Python 2中的以下作品

print ("|").center(11,'-')

When I try the same code in Python 3 I get the following error Message: 当我在Python 3中尝试相同的代码时,出现以下错误消息:

AttributeError: 'NoneType' object has no attribute 'center' AttributeError:“ NoneType”对象没有属性“ center”

How would one do the same thing in Python 3? 在Python 3中如何做同样的事情?

>>> print("|".center(11, '-'))
-----|-----

In Python 3 print is a function so you need to do the centering inside - otherwise you'd call it on the return value of print . 在Python 3中print是一个函数,因此您需要在内部居中-否则将在print的返回值上调用它。


Additionally, in Python 2 you should not put parentheses there at all: 此外,在Python 2中,您根本不应在其中放括号:

>>> print "|".center(11, '-')
-----|-----

The reason why it works with parentheses is that (foo) and foo are the same thing. 它使用括号的原因是(foo)foo是同一件事。

Another option to make it work in both Python 2 and Python 3 would be to add from __future__ import print_function to the top of your file and then use the Python 3 syntax. 使它在Python 2和Python 3中都可以使用的另一种方法是from __future__ import print_function添加到文件顶部,然后使用Python 3语法。

print a function, so your code in Python 3 is calling center() on the return value of print function (which is None). print函数,因此您在Python 3中的代码在print函数的返回值(无)上调用center() )。 Add one more pair of parenthesis: 再加上一对括号:

print( ("|").center(11,'-') )

f字符串解决方案是;

print(f'{"|":-^11}')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM