1

I have a list of words of variable length and want to add spaces (" ") to every word which is shorter than the longest word. I am later dividing this into sublists and therefore want every sublist in this list to be the same length!

My list of words could look like this:

words = ['sax', 'stol', 'kul', 'kök', 'äpple', 'rum', 'katt', 'toalettrulle']

So far my code looks like this:

len_list = []
for word in words:
    len_list.append(len(word))
max_word_size = max(len_list)

for item in words:
    len_item = len(item)
    if len_item < max_word_size:
        add_space = int(max_word_size - len_item)
        words.append(" " * add_space)
    else:
        break

This gives me spaces added to the end of my list, which is not what I want. Does anyone have an idea how to fix this?

Yevhen Kuzmovych
  • 10,940
  • 7
  • 28
  • 48
Lucky
  • 33
  • 6
  • 1
    May i ask the reason behind wanting each item to be of same length? This might be a little off, but if it's for the sake of outputting you could [have a look at this](https://stackoverflow.com/questions/9989334/create-nice-column-output-in-python) – tbjorch Feb 19 '21 at 12:25
  • Because you are just adding a new string of spaces to your `words` list. While you should be adding the spaces to the `item` and updating it in the list. – Yevhen Kuzmovych Feb 19 '21 at 12:26
  • Are you sure you don't mean ```item += " " * add_space```, instead of ```words.append(" " * add_space)```? Then updating the list with this, as @Yehven says. –  Feb 19 '21 at 12:27
  • appending is used to add item ( in your case spaces ) at the end of list , this is how list works. – Abhishek Chauhan Feb 19 '21 at 17:07

2 Answers2

3

You can do the following, using str.ljust to pad the shorter words:

words = ['sax', 'stol', 'kul', 'kök', 'äpple', 'rum', 'katt', 'toalettrulle']

ml = max(map(len, words))  # maximum length
words = [w.ljust(ml) for w in words]  # left justify to the max length


# OR, in order to make it a mutation on the original list
# words[:] = (w.ljust(ml) for w in words)

Note that strings themselves are immutable, so you cannot append spaces to them, you will have to rebuild the list with (new) padded strings.

user2390182
  • 72,016
  • 6
  • 67
  • 89
0

Not the perfect answer as i used a new list, Here is my code:

words = ['sax', 'stol', 'kul', 'kök', 'äpple', 'rum', 'katt', 'toalettrulle']
new_words =[]

len_list = []
for word in words:
    len_list.append(len(word))
    max_word_size = max(len_list)


for item in words:
    len_item = len(item)
    if len_item < max_word_size:
        add_space = int(max_word_size - len_item)
        new_item = item +(add_space*" ")
        new_words.append(new_item)
    else:
        new_words.append(item)
        break
print(new_words)
Abhishek Chauhan
  • 365
  • 3
  • 11