'Correctly handling ANSI escaped strings in Python 3

I use ANSI escaped strings in python 3/Ubuntu for printing e.g. colored text to the terminal. When I now try to find the "correct" length of such a string, this fails due to the fact that non printable "chars" get counted too, e.g.

len('\x1b[35mtest string\x1b[0m') is 25 even though the printable text's length only is 12.

I am hardly looking for a regex (if this could be suitable approach) that converts such a string into a list like so

['\x1b[35m', 'test string', '\x1b[0m']

The string could be more complex, e.g. multiple parts are colored, so the resulting list might get "longer"...

From there I would correctly calculate the length of such a string, and more importantly this would allow me to calculate a substring incl. resp. ANSI sequences like

'\x1b[35mtest string\x1b[0m'[0:4] --> \x1b[35mtest\x1b[0m

Thank you for any hint



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source