如何右对齐名称列表

时间:2014-04-21 14:05:53

标签: 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 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 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

我知道这是一个老问题,但这将在一行中完成:

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

这个列表理解的答案帮助了我:Call int() function on every list element?