600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > python中右对齐_python中如何右对齐-问答-阿里云开发者社区-阿里云

python中右对齐_python中如何右对齐-问答-阿里云开发者社区-阿里云

时间:2019-06-12 11:17:01

相关推荐

python中右对齐_python中如何右对齐-问答-阿里云开发者社区-阿里云

例如,有一个字典如下:

dic = {

"name": "botoo",

"url": "",

"page": "88",

"isNonProfit": "true",

"address": "china",

}

想要得到的输出结果如下:

首先获取字典的最大值max(map(len, dic.keys()))

然后使用

Str.rjust() 右对齐

或者

Str.ljust() 左对齐

或者

Str.center() 居中的方法有序列的输出。

dic = {

"name": "botoo",

"url": "",

"page": "88",

"isNonProfit": "true",

"address": "china",

}

d = max(map(len, dic.keys())) #获取key的最大值

for k in dic:

print(k.ljust(d),":",dic[k])

name : botoo

url :

page : 88

isNonProfit : true

address : china

for k in dic:

print(k.rjust(d),":",dic[k])

name : botoo

url :

page : 88

isNonProfit : true

address : china

for k in dic:

print(k.center(d),":",dic[k])

name : botoo

url :

page : 88

isNonProfit : true

address : china

关于 str.ljust()的用法还有这样的;

s = "adc"

s.ljust(20,"+")

'adc+++++++++++++++++'

s.rjust(20)

' adc'

s.center(20,"+")

'++++++++adc+++++++++'

问题来源于python学习网

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。