python怎么右对齐-Python教程

资源魔 21 0

例如,有一个字典以下:

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

想要失去的输入后果以下:

qq.png

相干保举:《Python视频教程》

起首猎取字典的最年夜值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+++++++++'
>>>

以上就是python怎样右对齐的具体内容,更多请存眷资源魔其它相干文章!

标签: Python python教程 python编程 python使用问题 右对齐

抱歉,评论功能暂时关闭!