Reputation: 33
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?
Upvotes: 1
Views: 72
Reputation: 421
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)
Upvotes: 0
Reputation: 73450
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.
Upvotes: 3