Python 如何右对齐名称列表

Python 如何右对齐名称列表,python,python-3.x,Python,Python 3.x,我一直在开发一个程序,要求用户输入一个姓名列表。在他们输入这些名称后,我的程序必须右对齐所有这些名称。这就是我到目前为止所做的: 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

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

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

我知道这是一个老生常谈的问题,但这只需要一句话:

print('\n'.join( [ name.rjust(len(max(names, key=len))) for name in names ] ))

这个列表理解的答案帮助了我:

有什么问题吗?你几乎有相同的输出…每个单词的左边多了一个空格,但我现在有了正确的答案。无论如何,谢谢你。你对这个问题有一个很好的答案。然而,为了简单地纠正您的版本中的问题,只需要有额外的空间就成了问题。额外的空间来自对
print()
函数使用多个参数。所有参数将用空格分隔。您想要做的是将
title
name
变量连接起来并打印出来。