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)

结果,,呃呃, 点个赞再走吧!
在这里插入图片描述

  • 7
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值