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
Python len() Function The len() function returns the number of items in an object. When the object is a string, the len() function returns the number of characters in the string.
The function len() is one of Python's built-in functions. It returns the length of an object. For example, it can return the number of items in a list. You can use the function with many different data types.
Python has got in-built method – len() to find the size of the list i.e. the length of the list. The len() method accepts an iterable as an argument and it counts and returns the number of elements present in the list.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With