gpt4 book ai didi

python - 如何右对齐姓名列表

转载 作者:行者123 更新时间:2023-12-01 05:16:09 25 4
gpt4 key购买 nike

我一直在开发一个程序,要求用户输入名称列表。他们输入这些名称后,我的程序必须右对齐所有这些名称。这是我到目前为止所拥有的:

names =[]

# User is prompted to enter a list of names
name = input ("Enter strings (end with DONE):\n")
while name != 'DONE':
names.append(name) # This appends/adds the name(s) the user types in, to names
name = input("")

print("\n""Right-aligned list:")
for name in names:
maximum = max(names, key=len) #This line of code searches for the name which is the longest
new_maximum = len(maximum) #Here it determines the length of the longest name
diff = new_maximum - len(name) #This line of code is used to subtract the length of the longest name from the length of another different name
title = diff*' ' #This code determines the open space (as the title) that has to be placed in front of the specific name
print(title,name)

这是没有所有注释的程序:

names =[]

name = input ("Enter strings (end with DONE):\n")
while name != 'DONE':
names.append(name)
name = input("")

print("\n""Right-aligned list:")
for name in names:
maximum = max(names, key=len)
new_maximum = len(maximum)
diff = new_maximum - len(name)
title = diff*' '
print(title,name)

我想要这个程序的输出是:

Enter strings (end with DONE):
Michael
James
Thabang
Kelly
Sam
Christopher
DONE

Right-aligned list:
Michael
James
Thabang
Kelly
Sam
Christopher

相反,这就是我得到的:

Enter strings (end with DONE):
Michael
James
Thabang
Kelly
Sam
Christopher
DONE

Right-aligned list:
Michael
James
Thabang
Kelly
Sam
Christopher

注意:当用户输入 DONE 时,提示就会结束。

问题是列表中的每个名称都会打印一个额外的空格。如何打印它右对齐但没有多余的空格?

最佳答案

您可以按如下方式使用字符串格式:

a = ['a', 'b', 'cd', 'efg']

max_length = max(len(i) for i in a)

for item in a:
print '{0:>{1}}'.format(item, max_length)

[OUTPUT]
a
b
cd
efg

关于python - 如何右对齐姓名列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23199050/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com