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?

4
  • 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 Commented Feb 19, 2021 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. Commented Feb 19, 2021 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. Commented Feb 19, 2021 at 12:27
  • appending is used to add item ( in your case spaces ) at the end of list , this is how list works. Commented Feb 19, 2021 at 17:07

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.