字符串对齐

字符串对齐工作是我们经常碰到的,在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的功能远不止这些,更多的希望大家可以自己探索
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值