wim*_*wim 7 python string pretty-print tty
有没有办法找到(甚至是最好的猜测)python中字符串的"打印"长度?例如'potaa\bto'是8个字符,len但在tty上只打印6个字符.
预期用途:
s = 'potato\x1b[01;32mpotato\x1b[0;0mpotato'
len(s) # 32
plen(s) # 18
Run Code Online (Sandbox Code Playgroud)
至少对于 ANSI TTY 转义序列,这是有效的:
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)
Run Code Online (Sandbox Code Playgroud)
印刷:
potato[01;32mpotato[0;0mpotato 32
potatopotatopotato 18
Run Code Online (Sandbox Code Playgroud)
对于退格 \b 或垂直制表符或 \r 与 \n - 这取决于它的打印方式和位置,不是吗?