python怎么右对齐

发布时间:2022-05-15 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了python怎么右对齐脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

例如,有一个字典如下:

@H_512_4@>>> 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怎么右对齐所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签:python