python右對齊的實例方法
例如,有一個字典如下:
>>> dic = {'name': 'botoo','url': '//www.jb51.net','page': '88','isNonProfit': 'true','address': 'china',}
想要得到的輸出結(jié)果如下:
name:botoourl:https:www.jb51.netpage:88isNonProfit:tureaddress:china
首先獲取字典的最大值max(map(len, dic.keys()))
然后使用
Str.rjust() 右對齊
或者
Str.ljust() 左對齊
或者
Str.center() 居中的方法有序列的輸出。
>>> dic = { 'name': 'botoo', 'url': '//www.jb51.net', 'page': '88', 'isNonProfit': 'true', 'address': 'china', }>>> >>> d = max(map(len, dic.keys())) #獲取key的最大值>>> >>> for k in dic: print(k.ljust(d),':',dic[k]) name : botoourl : //www.jb51.netpage : 88isNonProfit : trueaddress : china>>> for k in dic: print(k.rjust(d),':',dic[k]) name : botoo url : //www.jb51.net page : 88isNonProfit : true address : china>>> for k in dic: print(k.center(d),':',dic[k]) name : botoo url : //www.jb51.net page : 88isNonProfit : true address : china>>>
關于 str.ljust()的用法還有這樣的;
>>> s = 'adc'>>> s.ljust(20,'+')’adc+++++++++++++++++’>>> s.rjust(20)’adc’>>> s.center(20,'+')’++++++++adc+++++++++’>>>
知識點擴展:
python中對字符串的對齊操作
ljust()、rjust() 和 center()函數(shù)分別表示左對齊、右對齊、居中對齊
str.ljust(width[, fillchar]):左對齊,width -- 指定字符串長度,fillchar -- 填充字符,默認為空格;str.rjust(width[, fillchar]):右對齊,width -- 指定字符串長度,fillchar -- 填充字符,默認為空格;str.center(width[, fillchar]):居中對齊,width -- 字符串的總寬度,fillchar -- 填充字符,默認為空格。
test = ’hello world’print(test.ljust(20))print(test.ljust(20, ’*’))print(test.rjust(20, ’*’))print(test.center(20, ’*’))print(test.center(20)) #輸出結(jié)果如下:hello world******************hello world****hello world***** hello world
到此這篇關于python右對齊的實例方法的文章就介紹到這了,更多相關python中如何右對齊內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持好吧啦網(wǎng)!
相關文章:
1. 理解PHP5中static和const關鍵字2. IntelliJ IDEA安裝插件的方法步驟3. php模擬實現(xiàn)斗地主發(fā)牌4. .Net Core使用Coravel實現(xiàn)任務調(diào)度的完整步驟5. Vue封裝一個TodoList的案例與瀏覽器本地緩存的應用實現(xiàn)6. jQuery 實現(xiàn)DOM元素拖拽交換位置的實例代碼7. Vuex localStorage的具體使用8. vue 使用localstorage實現(xiàn)面包屑的操作9. spring acegi security 1.0.0 發(fā)布10. MyBatis中的JdbcType映射使用詳解

網(wǎng)公網(wǎng)安備