Reputation: 793
I have a problem:
I have a list that consists of elements of different lenghts:
det_slopes_JKH = ['Superpipe Bolgen','JatzPark','Avalanch Training Center','Bräma schwer']
and i would like to add spaces ' '
to the shorter words, with the purpose of having all the elements of the list with the same lenght.
det_slopes_JKH2 = []
for element in det_slopes_JKH:
if len(element) < len(element[2]:
det_slopes_JKH2.append(element + ' ')
Thanks
Upvotes: 1
Views: 89
Reputation: 67968
[x.ljust(len(max(det_slopes_JKH,key=len))) for x in det_slopes_JKH ]
You can try this one liner.
Upvotes: 0
Reputation: 25023
I haven't seen string formatting in the other answers and I happen to like formatting, that said I couldn't resist to show my 0.02 answer
maxlen = max(len(elt) for elt in places)
fmt = "%-"+str(maxlen)+"s"
places = [fmt%elt for elt in places]
Upvotes: 0
Reputation: 8709
You need two things:
max = len(max(det_slopes_JKH, key=len))
ljust()
as i.ljust(max)
. ljust
keeps adding spaces to right of string until string length = max. This can be done using list comprehension as:
>>> det_slopes_JKH = ['Superpipe Bolgen','JatzPark','Avalanch Training Center','Bräma schwer']
>>> [i.ljust(len(max(det_slopes_JKH, key=len))) for i in det_slopes_JKH]
['Superpipe Bolgen ', 'JatzPark ', 'Avalanch Training Center', 'Bräma schwer ']
Upvotes: 1
Reputation: 465
Your goal is not very clear but I am assuming you want to have all the strings of the same length.
This adds a space to each string until all are of the same length (the length of the longest string):
def equalize_lengths(l):
length = len(max(l, key=len))
return [e.ljust(length) for e in l]
Upvotes: 3
Reputation: 5061
Use builtin max
with key=len
it will give you maximum length string then use len
to get the length and then use string formatting
.
>>> max(det_slopes_JKH, key=len)
'Avalanch Training Center'
>>> len(max(det_slopes_JKH, key=len)
24
>>> ['{:24}'.format(elem) for elem in det_slopes_JKH]
['Superpipe Bolgen ', 'JatzPark ', 'Avalanch Training Center', 'Br\xc3\xa4ma schwer ']
>>>
Upvotes: 0
Reputation: 238131
This should do the trick:
det_slopes_JKH = ['Superpipe Bolgen','JatzPark','Avalanch Training Center','Bräma schwer']
max_length = max(len(elem) for elem in det_slopes_JKH)
det_slopes_JKH2 = [elem + ' '*(max_length - len(elem)) for elem in det_slopes_JKH]
print(det_slopes_JKH2)
Result is:
['Superpipe Bolgen ', 'JatzPark ', 'Avalanch Training Center', 'Bräma schwer ']
Upvotes: 0