python数字、字符串对齐

来源:互联网 发布:淘宝聚划算有什么好处 编辑:程序博客网 时间:2024/05/17 07:04


#!/usr/bin/python

data1=5

data2=10
str1 ='iot_history_%-2d'%data1 + ' ok'
str2 ='iot_history_%-2d'%data2 + ' ok'

print str1

print str2


输出:

iot_history_5  ok
iot_history_10 ok

'%*d'%(width,data)

上面的 * 对应 width,d 对应 data,输出的 data 占 width 个字符长度


或者直接

1
'%4d'%data

这样就是表明占4位,在%后面加一个 - 就是左对齐,位数可以通过len(max())获得



字符串对齐:

word="hello"

print word.center(20)      #居中输出,总共20个字符,word左右两侧各输出5个空格
print word.center(20,"*")    #居中输出,总共20个字符,word左右两侧各输出5个"*"号
print word.ljust(0)       #左对齐输出
print word.rjust(20)      #右对齐输出,总共20个字符,word占10个字符,因此左侧填充一个空格再输出word
print "%20s"%word          #类似于word.rjust(30

0 0
原创粉丝点击