Printed length of a string in python

后端 未结 3 1066
旧巷少年郎
旧巷少年郎 2021-02-14 19:35

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 pr

3条回答
  •  耶瑟儿~
    2021-02-14 19:44

    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?

提交回复
热议问题