Printed length of a string in python

wim picture wim · Feb 15, 2013 · Viewed 11.9k times · Source

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

Answer

dawg picture dawg · Feb 15, 2013

At least for the ANSI TTY escape sequence, this works:

import re
strip_ANSI_pat = re.compile(r"""
    \x1b     # literal ESC
    \[       # literal [
    [;\d]*   # zero or more digits or semicolons
    [A-Za-z] # a letter
    """, re.VERBOSE).sub

def strip_ANSI(s):
    return strip_ANSI_pat("", s)

s = 'potato\x1b[01;32mpotato\x1b[0;0mpotato'

print s, len(s)
s1=strip_ANSI(s)
print s1, len(s1)

Prints:

potato[01;32mpotato[0;0mpotato 32
potatopotatopotato 18

For backspaces \b or vertical tabs or \r vs \n -- it depends how and where it is printed, no?