• 技术文章 >后端开发 >Python教程

    python怎么右对齐

    爱喝马黛茶的安东尼爱喝马黛茶的安东尼2019-08-01 16:38:59原创5167

    例如,有一个字典如下:

    >>> 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怎么右对齐的详细内容,更多请关注php中文网其它相关文章!

    声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。
    专题推荐:python 右对齐
    上一篇:python学会了可以干什么 下一篇:python采用什么开源协议
    VIP课程(WEB全栈开发)

    相关文章推荐

    • 【腾讯云】年中优惠,「专享618元」优惠券!• python怎么不换行打印• python输出结果怎么换行• python怎么判断数据类型• python输出怎么保留两位小数
    1/1

    PHP中文网