前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python右对齐的实例方法

python右对齐的实例方法

作者头像
砸漏
发布2020-10-21 14:47:00
1.5K0
发布2020-10-21 14:47:00
举报
文章被收录于专栏:恩蓝脚本

例如,有一个字典如下:

代码语言:javascript
复制
    dic = {
"name": "botoo",
"url": "//www.zalou.cn",
"page": "88",
"isNonProfit": "true",
"address": "china",
}

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

name:botoo url:https:www.zalou.cn page:88 isNonProfit:ture address:china

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

然后使用

Str.rjust() 右对齐

或者

Str.ljust() 左对齐

或者

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

代码语言:javascript
复制
    dic = {
  "name": "botoo",
  "url": "//www.zalou.cn",
  "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     : //www.zalou.cn
page    : 88
isNonProfit : true
address   : china
    for k in dic:
  print(k.rjust(d),":",dic[k])
   
    name : botoo
    url : //www.zalou.cn
    page : 88
isNonProfit : true
  address : china
    for k in dic:
  print(k.center(d),":",dic[k])
   
  name  : botoo
  url   : //www.zalou.cn
  page  : 88
isNonProfit : true
 address  : china

关于 str.ljust()的用法还有这样的;

代码语言:javascript
复制
    s = "adc"
    s.ljust(20,"+")
'adc+++++++++++++++++'
    s.rjust(20)
'adc'
    s.center(20,"+")
'++++++++adc+++++++++'

知识点扩展:

python中对字符串的对齐操作

ljust()、rjust() 和 center()函数分别表示左对齐、右对齐、居中对齐

str.ljust(width[, fillchar]):左对齐,width — 指定字符串长度,fillchar — 填充字符,默认为空格; str.rjust(width[, fillchar]):右对齐,width — 指定字符串长度,fillchar — 填充字符,默认为空格; str.center(width[, fillchar]):居中对齐,width — 字符串的总宽度,fillchar — 填充字符,默认为空格。

代码语言:javascript
复制
test = 'hello world'
print(test.ljust(20))
print(test.ljust(20, '*'))
print(test.rjust(20, '*'))
print(test.center(20, '*'))
print(test.center(20))
 
#输出结果如下:
hello world*********
*********hello world
****hello world*****
  hello world   

到此这篇关于python右对齐的实例方法的文章就介绍到这了,更多相关python中如何右对齐内容请搜索ZaLou.Cn以前的文章或继续浏览下面的相关文章希望大家以后多多支持ZaLou.Cn!

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-09-11 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档