开发者社区> 问答> 正文

python中如何右对齐

python中如何右对齐

展开
收起
保持可爱mmm 2019-12-11 14:20:07 270 0
1 条回答
写回答
取消 提交回答
  • 例如,有一个字典如下:

    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() 居中的方法有序列的输出。

    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学习网

    2019-12-11 14:20:22
    赞同 展开评论 打赏
问答分类:
问答标签:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
From Python Scikit-Learn to Sc 立即下载
Data Pre-Processing in Python: 立即下载
双剑合璧-Python和大数据计算平台的结合 立即下载