gpt4 book ai didi

Python 使用 Format 方法格式化 ASCII 转义序列

转载 作者:太空宇宙 更新时间:2023-11-03 16:00:05 25 4
gpt4 key购买 nike

您好,我正在尝试使用 ASCII 转义序列很好地格式化带有颜色的表格,但是当我应用颜色时,格式化方法不会格式化字符串,导致表格不对齐。应用颜色 ASCII 转义序列后,格式方法未格式化字符串是否有原因?另外,是否有更好的方法来应用文本着色(注意,我无法在此系统上安装 Coloroma 或任何其他模块)?

下面是可用于演示该问题的可测试代码。

代码:

class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'

def disable(self):
self.HEADER = ''
self.OKBLUE = ''
self.OKGREEN = ''
self.WARNING = ''
self.FAIL = ''
self.ENDC = ''


def pass_fail(color, string):
if color == 'red':
return bcolors.FAIL + string + bcolors.ENDC
elif color == 'green':
return bcolors.OKGREEN + string + bcolors.ENDC
elif color == 'yellow':
return bcolors.WARNING + string + bcolors.ENDC

print('\n')
line_sep = '\t+' + ('-' * 57) + '+'
format_table = line_sep + '\n' + '\t| {:<42} | {:^10} |'

Critical = 100
Major = 200
Minor = 10

print('')
print(format_table.format('Number of Critical Issues Are: ', str(Critical)))
print(format_table.format('Number of Major Issues Are: ', str(Major)))
print(format_table.format('Number of Minor Issues Are: ', (Minor)))
print(line_sep)


print('')
print(format_table.format('Number of Critical Issues Are: ', pass_fail('green', str(Critical))))
print(format_table.format('Number of Major Issues Are: ', pass_fail('red', str(Major))))
print(format_table.format('Number of Minor Issues Are: ', pass_fail('yellow', str(Minor))))
print(line_sep)

第一个输出没有正确设置颜色格式:

+---------------------------------------------------------+
| Number of Critical Issues Are: | 100 |
+---------------------------------------------------------+
| Number of Major Issues Are: | 200 |
+---------------------------------------------------------+
| Number of Minor Issues Are: | 10 |
+---------------------------------------------------------+

未应用带有颜色格式的第二个输出:

+---------------------------------------------------------+
| Number of Critical Issues Are: | 100 |
+---------------------------------------------------------+
| Number of Major Issues Are: | 200 |
+---------------------------------------------------------+
| Number of Minor Issues Are: | 10 |
+---------------------------------------------------------+

最佳答案

字符串 format 方法确实正在格式化您的字符串,但在确定填充时,它在字符串长度计数中包含所有 ANSI Color Escape 字符。

要检查这一点:len(pass_fail('yellow', str(Minor)))

此问题的解决方案是重新设计字符串格式,以便 ANSI 颜色代码 字符不会欺骗格式化程序。您可能必须通过手动调整列宽来完成此操作。

关于Python 使用 Format 方法格式化 ASCII 转义序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40392911/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com