How to use map to pad characters "_" to strings whose length is less?

Viewed 55

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']))
3 Answers

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']

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']

Using string formatting, see link.

def all_eq(lst):
    max_item = len(max(lst, key=len))
    return list(map(f'{{:_<{max_item}}}'.format, lst))

In this case the padding character take place to the end of the string. Change with > for the opposite behavior.


A more flexible way. Supported paddings: <, '>', '^' (centered)

def all_eq(lst, padding='<', sep='_'):
    max_item = len(max(lst, key=len))
    return list(map(f'{{:{sep}{padding}{max_item}}}'.format, lst))

lst = ['photo', 'music', 'magazine']

print(all_eq(lst, padding='^', sep='@'))
#['@photo@@', '@music@@', 'magazine']
Related