In Python 3.4.3, I tried to justify some fields in width using the string.format () operator, and it seems to count control characters of zero length relative to the total width. Code example:
ANSI_RED = "\033[31m"
ANSI_DEFAULT="\033[39m\033[49m"
string1 = "12"
string2 = ANSI_RED+"12"+ANSI_DEFAULT
print("foo{:4s}bar".format(string1))
print("foo{:4s}bar".format(string2))
This will output:
foo12 bar
foo12bar
(with the second output having "12" in red, but I cannot reproduce this in SO)
In the second case, I lost my field width, I suppose, because Python saw that the total number of characters in the string was greater than the width, despite the fact that most of these characters result in zero length on the ANSI-related terminal.
What a clean way to have ANSI colors and working width?
source
share