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

相关文章

在前一篇博客中我们介绍了加侧旋的乒乓球弧圈技术的模拟,本...
在近期conda的版本更新中,有可能会删除路径下的_sysconfigd...
本文主要展示了一些lambda表达式的使用示例,通过这些示例,...
本文通过对比Jax和Numpy计算Normalized Hamming Distance的过...
我们知道GPU加速在可并行化程度比较高的算法中,能够发挥出比...
Numpy这个库在Python编程中非常的常用,不仅在性能上补足了P...