您的位置:首页 > 编程语言 > Python开发

python数字、字符串对齐

2015-10-21 15:31 681 查看
#!/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

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

或者直接
这样就是表明占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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: