python基礎===對字符串進行左右中對齊


例如,有一個字典如下:

>>> dic = {
"name": "botoo",
"url": "http://www.123.com",
"page": "88",
"isNonProfit": "true",
"address": "china",
}

想要得到的輸出結果如下:

 

首先 獲取字典 的 最大值   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+++++++++'
>>> 

 

順便提一下

如果有任何問題,你可以在這里找到我 ,軟件測試交流qq群,209092584

 


 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM