有什么方法可以找到(甚至是最好的猜测)python中字符串的“打印”长度吗?例如。 'potaa \ bto'是len
中的8个字符,但只有6个字符宽度打印在tty上。python中字符串的打印长度
预期使用:
s = 'potato\x1b[01;32mpotato\x1b[0;0mpotato'
len(s) # 32
plen(s) # 18
有什么方法可以找到(甚至是最好的猜测)python中字符串的“打印”长度吗?例如。 'potaa \ bto'是len
中的8个字符,但只有6个字符宽度打印在tty上。python中字符串的打印长度
预期使用:
s = 'potato\x1b[01;32mpotato\x1b[0;0mpotato'
len(s) # 32
plen(s) # 18
至少在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)
打印:
potato[01;32mpotato[0;0mpotato 32
potatopotatopotato 18
对于退格\ B或垂直制表符或\ r vs \ n - 这取决于打印的方式和位置,不是?
字符串的打印长度取决于字符串的类型。
python 2.x中的正常字符串在utf-8中。 utf-8的长度为 ,等于字符串中的字节数。将类型更改为unicode,len() 现在提供打印的标志。因此,格式化的工作原理:
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)
没关系,我误读了questiom – 2013-02-15 06:46:53
什么是' “ABC”''的plen'? “123 \ t456”'怎么样? ' “12345个\ R67”'? '“123456 \ n789”'? '“123456 \ r78 \ n9abcd”'?基本上,你必须决定你的字符集的规则并编写一个算法。 – 2013-02-15 06:56:56
这真的很难。我尝试了不同的方法,包括一些'subprocess.Popen(...)。communicate()'尝试,但无济于事。 – 2013-02-15 07:14:48