3

对于长度小于最小值的任何名称,将列表中的该项替换为包含名称的新字符串,并在右侧添加空格以达到最小长度。

例如,如果列表包含名称“Sue”且最小长度为 5,则该项目将替换为填充有 2 个空格的名称:“Sue”。任何已经达到最小长度或更长的名称都不会改变。

for words in list_of_names:  
    if len(words) < min_length:  
        answer = min_length - len(words)    

现在我想得到答案*并将该数量的空格添加回列表中。

4

3 回答 3

3

高级字符串格式允许您分配特定的宽度

>>> ['{:<5}'.format(x) for x in list_of_words]
['Sue  ', 'Alicia', 'Jen  ']
于 2012-11-07T05:30:16.610 回答
0

不确定,但是:

if len(word) < minSize:
    word += ' ' * (minSize - len(word))

或者:

correct_size = lambda word, size: word if len(word) >= size else word + ' ' * (size - len(word))
correct_size('test', 6)
>>> 'test  '

什么意思:

size = 6
lVals = ['test', 'where', 'all', 'simple', 'cases', 'tested']
lVals = [correct_size(word, size) for word in lVals]
print lVals
>>> ['test  ', 'where ', 'all   ', 'simple', 'cases ', 'tested']
于 2012-11-07T06:06:02.480 回答
0

您可以使用它str.ljust()来执行此操作:

list_of_words = ['Sue', 'Alicia', 'Jen']

new_list = []
for word in list_of_words:
    if len(word) < 5:
        new_list.append(word.ljust(5))
    else:
        new_list.append(word)

print(new_list)
于 2012-11-07T05:21:19.453 回答