String alignment does not work with ansi colors

家住魔仙堡 提交于 2020-07-08 11:59:30

问题


Facing this issue with Python:

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

As you can see the right-justification stopped working once the coloring tags get added to the text. The second "text" should be indented as the first one, but it was not.


回答1:


This is to be expected because the data is already longer than your field width:

>>> len(b)
13
>>> len('{0:>10}'.format(b))
13

To see a workaround, check here: Printed length of a string in python (in particular, the answer from user dawg)



来源:https://stackoverflow.com/questions/48816914/string-alignment-does-not-work-with-ansi-colors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!