简体   繁体   中英

Python 3 equivalent of Python 2 center

The following Works in Python 2

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

When I try the same code in Python 3 I get the following error Message:

AttributeError: 'NoneType' object has no attribute 'center'

How would one do the same thing in 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 .


Additionally, in Python 2 you should not put parentheses there at all:

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

The reason why it works with parentheses is that (foo) and foo are the same thing.

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.

print a function, so your code in Python 3 is calling center() on the return value of print function (which is None). Add one more pair of parenthesis:

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

f字符串解决方案是;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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