Python’s `str.format()`, fill characters, and ANSI colors

前端 未结 2 1330
终归单人心
终归单人心 2020-12-16 01:11

In Python 2, I’m using str.format() to align a bunch of columns of text I’m printing to a terminal. Basically, it’s a table, but I’m not printing any borders o

2条回答
  •  攒了一身酷
    2020-12-16 01:52

    Python doesn't distinguish between 'normal' characters and ANSI colour codes, which are also characters that the terminal interprets.

    In other words, printing '\x1b[92m' to a terminal may change the terminal text colour, Python doesn't see that as anything but a set of 5 characters. If you use print repr(line) instead, python will print the string literal form instead, including using escape codes for non-ASCII printable characters (so the ESC ASCII code, 27, is displayed as \x1b) to see how many have been added.

    You'll need to adjust your column alignments manually to allow for those extra characters.

    Without your actual code, that's hard for us to help you with though.

提交回复
热议问题