微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

python怎么右对齐

例如,有一个字典如下:

>>> 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+++++++++'
>>>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐