簡體   English   中英

相當於Python 2中心的Python 3

[英]Python 3 equivalent of Python 2 center

Python 2中的以下作品

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

當我在Python 3中嘗試相同的代碼時,出現以下錯誤消息:

AttributeError:“ NoneType”對象沒有屬性“ 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語法。

print函數,因此您在Python 3中的代碼在print函數的返回值(無)上調用center() )。 再加上一對括號:

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

f字符串解決方案是;

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM