如何将名字列表右对齐
我正在做一个程序,这个程序会让用户输入一串名字。在用户输入完这些名字后,我的程序需要把所有名字右对齐。到目前为止,我的进展是这样的:
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时,程序会结束。
问题是,列表中的每个名字前面都多了一个空格。我该怎么做才能让名字右对齐,但又不出现多余的空格呢?
2 个回答
1
我知道这个问题已经很久了,但用一行代码就能解决:
print('\n'.join( [ name.rjust(len(max(names, key=len))) for name in names ] ))
这个关于列表推导的回答帮了我很多:如何对每个列表元素调用 int() 函数?
1
你可以这样使用字符串格式化:
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