This is a very late answer, left as breadcrumbs for anyone who finds this page, trying to format text with built-in ANSI color codes.
byoungb 's comment about making debugging along the length of pre-painted text is exactly right. But if you already have colored text, here is a workaround:
See my ansiwrap module on PyPI. Its main goal is to provide textwrap for text text with ANSI, but it also exports ansilen() , which tells you, "how long will this line be if it does not contain ANSI control codes"? This is very useful when deciding on formatting, column width, and wrapping on pre-colored text. Add width - ansilen(s) spaces to the end or beginning of s left (or, respectively, to the right) to justify s in the column of the desired width . For example:.
def ansi_ljust(s, width): needed = width - ansilen(s) if needed > 0: return s + ' ' * needed else: return s
In addition, if you need to split, truncate, or combine colored text at some point, you will find that the nature of ANSI's stateful nature makes this difficult. You may find ansi_terminate_lines() useful; it โcorrectsโ the list of substrings, so that each of them has independent stand-alone ANSI codes with an equivalent effect as the source string.
Recent versions of ansicolors also contain an equivalent implementation of ansilen() .
Jonathan eunice
source share