本文需要Python 3.0+
函數format()可以用來很容易的對齊字符串。 你要做的就是使用<,>或者^字符后面緊跟一個指定的寬度。比如:
>>>format(text,'>20')
' Hello World'
>>>format(text,'<20')
'Hello World '
>>>format(text,'^20')
' Hello World '
>>>
如果你想指定一個非空格的填充字符,將它寫到對齊字符的前面即可:
>>>format(text,'=>20s')
'=========Hello World'
>>>format(text,'*^20s')
'****Hello World*****'
>>>
當格式化多個值的時候,這些格式代碼也可以被用在format()方法中。比如:
>>>'{:>10s} {:>10s}'.format('Hello','World')
' Hello World'
>>>
format()函數的一個好處是它不僅適用于字符串。它可以用來格式化任何值,使得它非常的通用。 比如,你可以用它來格式化數字:
>>>x=1.2345
>>>format(x,'>10')
' 1.2345'
>>>format(x,'^10.2f')
' 1.23 '
>>>
以上內容引自 http://python3-cookbook.readthedocs.io/zh_CN/latest/c02/p13_aligning_text_strings.html
使用以上方法我們打印一首帶格式的詩:
widthofline = 80
print("\n")
print(format(' The Zen of Python '.upper(), '#^{}s'.format(widthofline)))
zenofpythons = '''
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
'''
lines = zenofpythons.split("\n")
for line in lines:
print("#", format(line, '^{}s'.format(widthofline-4)), "#")
print("#" * widthofline)
運行上面的程序,可以看到下面的結果:
############################## THE ZEN OF PYTHON ###############################
# #
# Beautiful is better than ugly. #
# Explicit is better than implicit. #
# Simple is better than complex. #
# Complex is better than complicated. #
# Flat is better than nested. #
# Sparse is better than dense. #
# Readability counts. #
# Special cases aren't special enough to break the rules. #
# Although practicality beats purity. #
# Errors should never pass silently. #
# Unless explicitly silenced. #
# In the face of ambiguity, refuse the temptation to guess. #
# There should be one-- and preferably only one --obvious way to do it. #
# Although that way may not be obvious at first unless you're Dutch. #
# Now is better than never. #
# Although never is often better than *right* now. #
# If the implementation is hard to explain, it's a bad idea. #
# If the implementation is easy to explain, it may be a good idea. #
# Namespaces are one honking great idea -- let's do more of those! #
# #
################################################################################
好玩吧?:) 有興趣的可以把以上代碼封裝一下。