Is there any way to find (even a best guess) the "printed" length of a string in python? E.g. 'potaa\bto' is 8 characters in len
but only 6 characters wide printed on a tty.
Expected usage:
s = 'potato\x1b[01;32mpotato\x1b[0;0mpotato'
len(s) # 32
plen(s) # 18
The bash shell had exactly the same need, in order to know when the user's typed input wraps to the next line, in the presence of non-printable characters in the prompt string. Their solution was to not even try - instead, they require that anyone setting a prompt string put
\[
and\]
around non-printing portions of the prompt. The printed length is calculated to be the length of the string, with these special sequences and all text between them filtered out. (The special sequences are omitted on output, of course.)At least for the ANSI TTY escape sequence, this works:
Prints:
For backspaces \b or vertical tabs or \r vs \n -- it depends how and where it is printed, no?
The printed length of a string depends on the type of the string.