python右對(duì)齊的實(shí)例方法
例如,有一個(gè)字典如下:
>>> 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() 右對(duì)齊
或者
Str.ljust() 左對(duì)齊
或者
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>>>
關(guān)于 str.ljust()的用法還有這樣的;
>>> s = 'adc'>>> s.ljust(20,'+')’adc+++++++++++++++++’>>> s.rjust(20)’adc’>>> s.center(20,'+')’++++++++adc+++++++++’>>>
知識(shí)點(diǎn)擴(kuò)展:
python中對(duì)字符串的對(duì)齊操作
ljust()、rjust() 和 center()函數(shù)分別表示左對(duì)齊、右對(duì)齊、居中對(duì)齊
str.ljust(width[, fillchar]):左對(duì)齊,width -- 指定字符串長(zhǎng)度,fillchar -- 填充字符,默認(rèn)為空格;str.rjust(width[, fillchar]):右對(duì)齊,width -- 指定字符串長(zhǎng)度,fillchar -- 填充字符,默認(rèn)為空格;str.center(width[, fillchar]):居中對(duì)齊,width -- 字符串的總寬度,fillchar -- 填充字符,默認(rèn)為空格。
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
到此這篇關(guān)于python右對(duì)齊的實(shí)例方法的文章就介紹到這了,更多相關(guān)python中如何右對(duì)齊內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. 低版本IE正常運(yùn)行HTML5+CSS3網(wǎng)站的3種解決方案2. XML入門(mén)的常見(jiàn)問(wèn)題(一)3. 詳解盒子端CSS動(dòng)畫(huà)性能提升4. Vue+elementUI下拉框自定義顏色選擇器方式5. CSS hack用法案例詳解6. XML入門(mén)的常見(jiàn)問(wèn)題(四)7. 告別AJAX實(shí)現(xiàn)無(wú)刷新提交表單8. CSS3實(shí)例分享之多重背景的實(shí)現(xiàn)(Multiple backgrounds)9. 使用css實(shí)現(xiàn)全兼容tooltip提示框10. css進(jìn)階學(xué)習(xí) 選擇符
