• 技术文章 >常见问题 >Python常见问题

    python中如何右对齐

    爱喝马黛茶的安东尼爱喝马黛茶的安东尼2019-11-20 11:53:56原创4642

    例如,有一个字典如下:

    1

    2

    3

    4

    5

    6

    7

    >>> dic = {

    "name": "botoo",

    "url": "http://www.123.com",

    "page": "88",

    "isNonProfit": "true",

    "address": "china",

    }

    想要得到的输出结果如下:

    首先获取字典的值max(map(len, dic.keys()))

    然后使用

    Str.rjust() 右对齐

    或者

    Str.ljust() 左对齐

    或者

    Str.center() 居中的方法有序列的输出。

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    33

    34

    35

    >>> 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()的用法还有这样的;

    1

    2

    3

    4

    5

    6

    7

    8

    >>> s = "adc"

    >>> s.ljust(20,"+")

    'adc+++++++++++++++++'

    >>> s.rjust(20)

    '                 adc'

    >>> s.center(20,"+")

    '++++++++adc+++++++++'

    >>>

    众多python培训视频,尽在python学习网,欢迎在线学习!

    专题推荐:python 右对齐
    上一篇:python的def是什么作用 下一篇:python中如何设置tab值

    相关文章推荐

    • Python是什么?• Python可以用来做什么?• Python是如何编译运行的• Python中的import是怎么实现的?• Python中__new__()和__init__()有什么区别?

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网