优雅的打印方式中间对齐的标题===";用python

优雅的打印方式中间对齐的标题===";用python,python,Python,正如我所知,有一些优雅的方式打印左对齐和右对齐字符串填充。 像这样 str = "left_justified" str.ljust(20, '0'); 或 用填充打印中间对齐字符串的最佳方法是什么?您错过了^: s = 'centered' print "{0:{1}^20}".format(s, "=") # -> ======centered====== 我还冒昧地将str变量重命名为不影响内置str的变量 >>> "hello".center(50, '=')

正如我所知,有一些优雅的方式打印左对齐和右对齐字符串填充。 像这样

str = "left_justified"
str.ljust(20, '0');


用填充打印中间对齐字符串的最佳方法是什么?您错过了
^

s = 'centered'
print "{0:{1}^20}".format(s, "=")
# -> ======centered======
我还冒昧地将
str
变量重命名为不影响内置
str
的变量

>>> "hello".center(50, '=')
'======================hello======================='
s = 'centered'
print "{0:{1}^20}".format(s, "=")
# -> ======centered======
>>> "hello".center(50, '=')
'======================hello======================='
>>> termwidth, fillchar = 78, '='
>>> print ' middle justified title '.center(termwidth, fillchar)
=========================== middle justified title ===========================