Pythonic方式如何实现右对齐打印值?

2 投票
3 回答
1271 浏览
提问于 2025-04-16 20:22

我有一串字符串,我想根据它们的结尾部分进行分组,然后把这些值打印出来,要求右对齐,左边用空格填充。

用Python怎么做比较好呢?

我现在的代码是:

def find_pos(needle, haystack):
    for i, v in enumerate(haystack):
        if str(needle).endswith(v):
            return i
    return -1

# Show only Error and Warning things
search_terms = "Error", "Warning"
errors_list = filter(lambda item: str(item).endswith(search_terms), dir(__builtins__))

# alphabetical sort
errors_list.sort()
# Sort the list so Errors come before Warnings
errors_list.sort(lambda x, y: find_pos(x, search_terms) - find_pos(y, search_terms))

# Format for right-aligning the string
size = str(len(max(errors_list, key=len)))
fmt = "{:>" + size + "s}"
for item in errors_list:
    print fmt.format(item)

我想到的另一个方法是:

size = len(max(errors_list, key=len))
for item in errors_list:
    print str.rjust(item, size)

我还在学习Python,所以如果有其他建议来改进代码也非常欢迎。

3 个回答

1

你可以看看这里,里面讲了怎么用str.rjust来右对齐文本,以及如何使用打印格式来实现。

8

非常接近。

fmt = "{:>{size}s}"
for item in errors_list:
    print fmt.format(item, size=size)
7
  1. 这两个排序步骤可以合并成一个:

    errors_list.sort(key=lambda x: (x, find_pos(x, search_terms)))
    

    一般来说,使用 key 参数比使用 cmp 更好。关于排序的文档

  2. 如果你本来就对长度感兴趣,使用 key 参数来配合 max() 就有点没必要了。我会选择:

    width = max(map(len, errors_list))
    
  3. 因为在循环中长度是不会改变的,所以我只需要准备一次格式字符串:

    right_align = ">{}".format(width)
    
  4. 在循环中,你现在可以使用免费的 format() 函数(也就是不是 str 方法,而是内置函数):

    for item in errors_list:
        print format(item, right_align)
    
  5. str.rjust(item, size) 通常更好写成 item.rjust(size)

撰写回答