例如,有⼀个字典如下:
>>> dic = {
\"name\": \"botoo\
\"url\": \"//www.jb51.net\\"page\": \"88\
\"isNonProfit\": \"true\\"address\": \"china\}
想要得到的输出结果如下:
name:botoo
url:https:www.jb51.netpage:88
isNonProfit:tureaddress:china
⾸先获取字典的最⼤值max(map(len, dic.keys()))然后使⽤Str.rjust() 右对齐或者
Str.ljust() 左对齐或者
Str.center() 居中的⽅法有序列的输出。
>>> dic = {
\"name\": \"botoo\
\"url\": \"//www.jb51.net\ \"page\": \"88\
\"isNonProfit\": \"true\ \"address\": \"china\ }>>>
>>> d = max(map(len, dic.keys())) #获取key的最⼤值>>>
>>> for k in dic:
print(k.ljust(d),\":\
name : botoo
url : //www.jb51.netpage : 88
isNonProfit : trueaddress : china>>> for k in dic:
print(k.rjust(d),\":\
name : botoo
url : //www.jb51.net page : 88
isNonProfit : true address : china>>> for k in dic:
print(k.center(d),\":\
name : botoo
url : //www.jb51.net page : 88
isNonProfit : true address : china>>>
关于 str.ljust()的⽤法还有这样的;
>>> 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 -- 填充字符,默认为空格。
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中如何右对齐内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!
因篇幅问题不能全部显示,请点此查看更多更全内容
Copyright © 2019- stra.cn 版权所有 赣ICP备2024042791号-4
违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务