栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

02 Python 指定长度输出字符,不足补空格,超出长度,切片

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

02 Python 指定长度输出字符,不足补空格,超出长度,切片

心急的伙伴直接拉到文章末尾看代码哈!

用Python对字典输出,或是对列表、元组输出

 st="There are moments in life when you miss someone so much that you just want to pick them from your dreams and hug them for real! Dream what you want to dream;go where you want to go;be what you want to be,because you have only one life and one chance to do all the things you want to do."
 dict={}#定义一个字典
    for j in st:
        if j in dict:
            dict[j]+=1
        else:
            dict[j]=1
    print(dict)

黑框一般是这样的

可是这样很难看,有没有什么办法让其对齐一点呢?我们改正后的代码:

    st="There are moments in life when you miss someone so much that you just want to pick them from your dreams and hug them for real! Dream what you want to dream;go where you want to go;be what you want to be,because you have only one life and one chance to do all the things you want to do."
    dict={}#定义一个字典
    for j in st:
        if j in dict:
            dict[j]+=1
        else:
            dict[j]=1
    for a in dict:
        s=a+"	"+str(dict[a])+'n'
        print(s)    

输出后,发现无法对齐,很不好看,如下图:

那有没有办法解决呢?有的,只需要让程序指定长度输出字符,不足补空格,超出长度,切片。代码如下:

    for a in dict:
    	#ljust(15)[:15],如果名称长度超过15个字符,
    	#则不会截断ljust.如果要以15个字符结尾,
    	#则可以对结果字符串进行切片。
         s=i.ljust(15)[:15]+str(dict[i])+'n'  
        print(s)  

效果是这样的啦:

当然还有其它办法,如:

 for a in dict:
        #s=a.ljust(15)[:15]+str(dict[a])+'n'  
        print("{:<15}".format(a),dict[a])

又或者:

for a in dict:
        #s=a.ljust(15)[:15]+str(dict[a])+'n'  
        #print("{:<15}".format(a),dict[a])
        #手动在后面敲15个空格,然后切片
        s = (a+"               ")[:15]+str(dict[a])
        print(s)

结果,,呃呃, 点个赞再走吧!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/348354.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号