字符串对齐工作是我们经常碰到的,在python cookbook中有那么一小节有讲述,总结如下:
@python
>>>text='hello world'
>>>text.rjust(20)
' hello world'
>>>text.ljust(20)
'hello world '
>>>text.center(20)
' hello world '
#上面三个例子就是ljust,rjust,center的对齐工作了
#当然,还有厉害点的
>>>text.rjust(30,'*')
'*******************hello world'
>>>text.ljust(30,'=')
'hello world==================='
>>>text.center(30,'*')
'*********hello world**********'
#其实对于上述三个字符串对齐方法,都可以用一个format方法来解决的.看自己喜好:
>>>format(text,'>20')#右对齐
' hello world'
>>>format(text,'<20')#左对齐
'hello world '
>>>format(text,'^20')#居中
' hello world '
#用format当然也是可以替换空白符的了
>>>format(text,'*>20')#只需要将你想要的字符放在缩进方向前面即可
'*********hello world'
>>>format(text,'=<20')
'hello world========='
>>>format(text,'*^20')
'****hello world*****'
#Note that:替换字符只能单个字符,比如:
>>>format(text,'*=^20')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Invalid conversion specification
#format的功能远不止这些,更多的希望大家可以自己探索