python右對齊的實例方法
例如,有一個字典如下:
>>> dic = {
"name": "botoo",
"url": "http://www.dhdzp.com",
"page": "88",
"isNonProfit": "true",
"address": "china",
}
想要得到的輸出結果如下:
name:botoo
url:https:www.dhdzp.com
page:88
isNonProfit:ture
address:china
首先獲取字典的最大值max(map(len, dic.keys()))
然后使用
Str.rjust() 右對齊
或者
Str.ljust() 左對齊
或者
Str.center() 居中的方法有序列的輸出。
>>> dic = {
"name": "botoo",
"url": "http://www.dhdzp.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 : //www.dhdzp.com
page : 88
isNonProfit : true
address : china
>>> for k in dic:
print(k.rjust(d),":",dic[k])
name : botoo
url : //www.dhdzp.com
page : 88
isNonProfit : true
address : china
>>> for k in dic:
print(k.center(d),":",dic[k])
name : botoo
url : //www.dhdzp.com
page : 88
isNonProfit : 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)) #輸出結果如下: hello world********* *********hello world ****hello world***** hello world
到此這篇關于python右對齊的實例方法的文章就介紹到這了,更多相關python中如何右對齊內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
一文詳解如何在Python中實現(xiàn)switch語句
這篇文章主要給大家介紹了關于如何在Python中實現(xiàn)switch語句的相關資料,今天在學習python的過程中,發(fā)現(xiàn)python沒有switch這個語法,所以這里給大家總結下,需要的朋友可以參考下2023-09-09
Python3 適合初學者學習的銀行賬戶登錄系統(tǒng)實例
下面小編就為大家?guī)硪黄狿ython3 適合初學者學習的銀行賬戶登錄系統(tǒng)實例。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-08-08
odoo?為可編輯列表視圖字段搜索添加查詢過濾條件的詳細過程
Odoo 是基于 Python 寫的一系列開源商業(yè)應用程序套裝,前身是 OpenERP,這篇文章主要介紹了odoo?為可編輯列表視圖字段搜索添加查詢過濾條件,需要的朋友可以參考下2023-02-02

