Print string length in python

Is there a way to find (even a better guess) the "printed" string length in python? For instance. 'potaa \ bto' - 8 characters in len , but only 6 characters printed in tty.

Expected Use:

 s = 'potato\x1b[01;32mpotato\x1b[0;0mpotato' len(s) # 32 plen(s) # 18 
+6
source share
2 answers

At a minimum, 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) 

Print

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

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

+1
source

The printed string length depends on the type of string.

The normal lines in python 2.x are in utf-8. Utf-8 is equal in length to bytes in String. Change the type to unicode, len () now supplies the printed characters. Therefore formatting works:

 value = 'abcÀâücdf' len_value = len(value) len_uvalue = len(unicode(value,'utf-8')) size = self['size'] + len_value-len_uvalue print value[:min(len(value),size)].ljust(size) 
+1
source

All Articles