字符串对齐不适用于 ansi 颜色

5 python printing format text colors

用 Python 面对这个问题:

a = "text"
print('{0:>10}'.format(a))
# output:      text
b = "\x1b[33mtext\x1b[0m"
print('{0:>10}'.format(b))
# output: text
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,一旦将着色标签添加到文本中,右对齐就停止工作。第二个“文本”应该与第一个缩进,但事实并非如此。

wim*_*wim 1

这是可以预料的,因为数据已经比您的字段宽度长:

>>> len(b)
13
>>> len('{0:>10}'.format(b))
13
Run Code Online (Sandbox Code Playgroud)

要查看解决方法,请检查此处: Printed length of a string in python(特别是用户 dawg 的答案