Does Python count zero-length control characters in a string formatting width field?

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?

+4
source share
3

ANSI ?

, escape-, .

len() Python 2 Python 3 str. ( ):

>>> s = 'abc\bde'
>>> print s
abcde
>>> len(s)
6

, , - , (.. , escape- ANSI).

+1

, "", - : [/p >

print("foo{0}{1:4s}{2}bar".format(ANSI_RED, string1, ANSI_DEFAULT))
+1

Correctly using terminal control codes is very difficult (as seen below, not all of them have a certain width), so it is best to use explicit column movement.

# string2 defined as above
def col(n): return "\033[{:d}G".format(n)
print("foo{:s}{:s}bar".format(string2,col(8)))

Conclusion:

foo12  bar
+1
source

Source: https://habr.com/ru/post/1599766/


All Articles