例如,有一個字典如下:
>>> 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() 居中的方法有序列的輸出。
>>> 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://www.123.com page : 88 isNonProfit : true address : china >>> for k in dic: print(k.rjust(d),":",dic[k]) name : botoo url : http://www.123.com page : 88 isNonProfit : true address : china >>> for k in dic: print(k.center(d),":",dic[k]) name : botoo url : http://www.123.com page : 88 isNonProfit : true address : china >>>
關於 str.ljust()的用法還有這樣的;
>>> s = "adc" >>> s.ljust(20,"+") 'adc+++++++++++++++++' >>> s.rjust(20) ' adc' >>> s.center(20,"+") '++++++++adc+++++++++' >>>
以上是怎麼右對齊的詳細內容。更多資訊請關注PHP中文網其他相關文章!