Python:使用str.ljust和map

时间:2015-11-25 20:51:13

标签: python-2.7

我正在重新审视我前一段时间写过的一些代码,并注意到我编写了自己的函数来填充带有空格的字符串。

我的原始代码:

def print_info(people):
    col_widths = [max(len(p[0]) for p in people) + 1, 10, 20]
    rows = [['Name', 'Job', 'Mood']] + [[p[0], p[1], p[2]] for p in people]
    rows = (map(pad_string_right, row, col_widths) for row in rows)
    print '\n'.join(''.join(row) for row in rows)

def pad_string_right(string, length):
    if(len(string) > length):
        raise ValueError
    char_difference = length - len(string)
    return string + (' ' * char_difference)

print_info([("Barry", "plumber", "happy"),
            ("Brian", "butcher", "bored"),
            ("Betty", "singer", "hungry")])

我想用内置的 str.ljust 替换 pad_string_right 函数,但在使用map时无法解决如何使用它。

1 个答案:

答案 0 :(得分:2)

简单地将pad_string_right替换为str.ljust中的map

def print_info(people):
    col_widths = [max(len(p[0]) for p in people) + 1, 10, 20]
    rows = [['Name', 'Job', 'Mood']] + [[p[0], p[1], p[2]] for p in people]
    rows = (map(str.ljust, row, col_widths) for row in rows)
    print '\n'.join(''.join(row) for row in rows)

def pad_string_right(string, length):
    if(len(string) > length):
        raise ValueError
    char_difference = length - len(string)
    return string + (' ' * char_difference)

print_info([("Barry", "plumber", "happy"),
            ("Brian", "butcher", "bored"),
            ("Betty", "singer", "hungry")])

输出:

Name  Job       Mood                
Barry plumber   happy               
Brian butcher   bored               
Betty singer    hungry