python右對齊的實例方法
例如,有一個字典如下:
>>> dic = { "name": "botoo", "url": "http://chabaoo.cn", "page": "88", "isNonProfit": "true", "address": "china", }
想要得到的輸出結(jié)果如下:
name:botoo
url:https:chabaoo.cn
page:88
isNonProfit:ture
address:china
首先獲取字典的最大值max(map(len, dic.keys()))
然后使用
Str.rjust() 右對齊
或者
Str.ljust() 左對齊
或者
Str.center() 居中的方法有序列的輸出。
>>> dic = { "name": "botoo", "url": "http://chabaoo.cn", "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 : //chabaoo.cn page : 88 isNonProfit : true address : china >>> for k in dic: print(k.rjust(d),":",dic[k]) name : botoo url : //chabaoo.cn page : 88 isNonProfit : true address : china >>> for k in dic: print(k.center(d),":",dic[k]) name : botoo url : //chabaoo.cn page : 88 isNonProfit : true address : china >>>
關(guān)于 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 -- 填充字符,默認(rèn)為空格;
str.rjust(width[, fillchar]):右對齊,width -- 指定字符串長度,fillchar -- 填充字符,默認(rèn)為空格;
str.center(width[, fillchar]):居中對齊,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右對齊的實例方法的文章就介紹到這了,更多相關(guān)python中如何右對齊內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python機器學(xué)習(xí)之基于Pytorch實現(xiàn)貓狗分類
看了許多關(guān)于PyTorch的入門文章,大抵是從torchvision.datasets中自帶的數(shù)據(jù)集進行訓(xùn)練,導(dǎo)致很難把PyTorch運用于自己的數(shù)據(jù)集上,真正地靈活運用PyTorch,本文詳細(xì)介紹了怎么利用Pytorch實現(xiàn)貓狗分類,需要的朋友可以參考下2021-06-06python實現(xiàn)快速文件格式批量轉(zhuǎn)換的方法
這篇文章主要介紹了python實現(xiàn)快速文件格式批量轉(zhuǎn)換的方法,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-10-10Python中使用ConfigParser解析ini配置文件實例
這篇文章主要介紹了Python中使用ConfigParser解析ini配置文件實例,本文給出了創(chuàng)建和讀取ini文件的例子,需要的朋友可以參考下2014-08-08Python利用Beautiful Soup模塊創(chuàng)建對象詳解
這篇文章主要介紹了Python利用Beautiful Soup模塊創(chuàng)建對象的相關(guān)資料,文中介紹的非常詳細(xì),相信對大家具有一定的參考價值,需要的朋友們下面來一起看看吧。2017-03-03