How to use map to pad characters "_" to strings whose length is less?
My code:
lst = ['photo', 'music', 'magazine']
def all_eq(lst):
max_item = max(lst, key = lambda x: len(x))
max_len = len(max_item)
for i in lst:
if len(i) < max_len:
b = list(map(lambda x: x "_", lst))
return b
print(all_eq(['photo', 'music', 'magazine']))
CodePudding user response:
You can use str.rjust
(or str.ljust
, depending on the desired padding direction).
rjust(self, width, fillchar=' ', /) Return a right-justified string of length width.
Padding is done using the specified fill character (default is a space).
Example:
>>> lst = ['photo', 'music', 'magazine']
>>> max_len = max(map(len, lst))
>>> padded = [e.rjust(max_len, "_") for e in lst]
>>> padded
['___photo', '___music', 'magazine']
CodePudding user response:
You could use f-string padding in a list comprehension:
>>> lst = ['photo', 'music', 'magazine']
>>> max_len = max(map(len, lst))
>>> [f'{s:_>{max_len}}' for s in lst]
['___photo', '___music', 'magazine']
>>> [f'{s:_<{max_len}}' for s in lst]
['photo___', 'music___', 'magazine']