Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printed length of a string in python

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
like image 971
wim Avatar asked Feb 15 '13 06:02

wim


People also ask

Is Len () in Python a string?

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.

What is print Len in Python?

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.

How do you find the length of a string in a list Python?

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.


1 Answers

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?

like image 144
dawg Avatar answered Oct 01 '22 11:10

dawg