小智 6
您可以使用 str.center
s = "hello world"
s.center(40)
>>> ' hello world '
Run Code Online (Sandbox Code Playgroud)
如果您正在使用python版本3.6
(因为我喜欢使用它而不是2.7
),您可以使用函数中的caret
字符format
:
>>> '{:^50}'.format('sample text')
' sample text ' # with a length of 50.
Run Code Online (Sandbox Code Playgroud)
如果你想填补你使用的空白:
>>> '{:*^50}'.format('sample text')
'*******************sample text********************' # * is the fill character.
Run Code Online (Sandbox Code Playgroud)
import shutil
def print_centre(s):
print(s.center(shutil.get_terminal_size().columns))
Run Code Online (Sandbox Code Playgroud)