我有这个简单的程序,它读取一个列表并将第一个字母大写,但我想将所有字符串的字符串长度固定为相同,然后输出到一个新列表,新字符串位于中间并填充到左侧是的-我见过不同的方法,但还没有让它们起作用。请任何人帮忙!谢谢!old_list = ['cow', 'dog', 'elephant', 'horse']new_list = []for item in old_list: new_list.append(item.capitalize()) print(item)for item in new_list: print(len(item))
2 回答

达令说
TA贡献1821条经验 获得超6个赞
对于可变宽度(最长字有限)
old_list = ['cow', 'dog', 'elephant', 'horse']
max = 0
for i in old_list:
if len(i) > max:
max = len(i)
new_list = []
for i in old_list:
new_list.append('{item:^{width}}'.format(item=i, width=max))
cow
dog
elephant
horse

白猪掌柜的
TA贡献1893条经验 获得超10个赞
您可以使用格式化字符串以固定宽度将它们居中
for i in new_list:
print('{:^12s}'.format(i))
输出
Cow
Dog
Elephant
Horse
在此示例中,所有字符串都设置为 12 个字符宽并且居中。
添加回答
举报
0/150
提交
取消