本文摘自php中文网,作者爱喝马黛茶的安东尼,侵删。

例如,有一个字典如下:
1 2 3 4 5 6 7 | >>> dic = {
"name" : "botoo" ,
"url" : "http://www.123.com" ,
"page" : "88" ,
"isNonProfit" : "true" ,
"address" : "china" ,
}
|
想要得到的输出结果如下:

相关推荐:《Python视频教程》
首先获取字典的最大值max(map(len, dic.keys()))
然后使用
Str.rjust() 右对齐
或者
Str.ljust() 左对齐
或者
Str.center() 居中的方法有序列的输出。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | >>> dic = {
"name" : "botoo" ,
"url" : "http://www.123.com" ,
"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 : http:
page : 88
isNonProfit : true
address : china
>>> for k in dic:
print (k.rjust(d), ":" ,dic[k])
name : botoo
url : http:
page : 88
isNonProfit : true
address : china
>>> for k in dic:
print (k.center(d), ":" ,dic[k])
name : botoo
url : http:
page : 88
isNonProfit : true
address : china
>>>
|
关于 str.ljust()的用法还有这样的;
1 2 3 4 5 6 7 8 | >>> s = "adc"
>>> s.ljust(20, "+" )
'adc+++++++++++++++++'
>>> s.rjust(20)
' adc'
>>> s.center(20, "+" )
'++++++++adc+++++++++'
>>>
|
以上就是python怎么右对齐的详细内容,更多文章请关注木庄网络博客!!
相关阅读 >>
Python线程下事件用法的简单介绍
Python中time模块需要安装么
Python爬虫经典例子有哪些
Python如何实现客户端和服务器端的数据传输(代码)
Python自学文件操作
Python怎么垂直输出
Python中什么表示空类型
Python学完基础学什么
Python实现读取json文件到excel表
Python 通过字符串调用对象属性或方法
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » python怎么右对齐