3

For any name whose length is less than the minimum, replace that item of the list with a new string containing the name with space(s) added to the right-hand side to achieve the minimum length.

For example, if the list contains the name "Sue" and the minimum length is 5, then that item would be replaced with the name padded with 2 spaces: "Sue  ". Any names that are already the minimum length or longer are unchanged.

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

Now i want to take the answer* and add that amount of spaces back into the list.

Cat
  • 66,919
  • 24
  • 133
  • 141

3 Answers3

3

Advanced string formatting allows you to assign specific width:

>>> ['{:<5}'.format(x) for x in list_of_words]
['Sue  ', 'Alicia', 'Jen  ']
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
0

You can use str.ljust() to do this:

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)
Marius
  • 58,213
  • 16
  • 107
  • 105
  • Thanks a lot! works and makes a lot of sense too bad I have 2 more questions to go in this problem set. I wouldnt ask here would I? Ill probably create a new post – AlwaysNeedsHelp Nov 07 '12 at 05:31
  • You should create new posts for other questions you have, since you'll probably need to come up with new bits of code that demonstrate the specific problem you're having and what you've tried. – Marius Nov 07 '12 at 05:57
  • @AlwaysNeedsHelp : Mark this answer as solved if you think this is the solution. – Tariq M Nasim Nov 07 '12 at 13:07
0

Not sure but:

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

OR:

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

What means:

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']
Artsiom Rudzenka
  • 27,895
  • 4
  • 34
  • 52