心急的伙伴直接拉到文章末尾看代码哈!
用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)
结果,,呃呃, 点个赞再走吧!