在Python中为ANSI颜色代码的字符串获取正确的字符串长度 [英] Getting correct string length in Python for strings with ANSI color codes
问题描述
我有一些Python代码将自动以漂亮的列格式打印一组数据,包括放入适当的ASCII转义序列来绘制各种数据以便阅读。
I've got some Python code that will automatically print a set of data in a nice column format, including putting in the appropriate ASCII escape sequences to color various pieces of the data for readability.
我最终以每行表示为列表,每个项目是一个空格填充的列,因此每行上的相同列总是相同的长度。不幸的是,当我真的打印这个,不是所有的列排列。我怀疑这是与ASCII转义序列有关 - 因为 len
函数似乎不能识别这些:
I eventually end up with each line being represented as a list, with each item being a column that is space-padded so that the same columns on each line are always the same length. Unfortunately when I actually go to print this, not all the columns line up. I suspect this is to do with the ASCII escape sequences - because the len
function doesn't seem to recognize these:
>>> a = '\x1b[1m0.0\x1b[0m'
>>> len(a)
11
>>> print a
0.0
所以每个列的长度根据 len
,它们在屏幕上打印时的长度实际上不一样。
And so while each column is the same length according to len
, they are not actually the same length when printed on the screen.
有没有办法(除了使用正则表达式做一些黑客,我宁愿不做)采取转义的字符串,找出打印长度是什么我可以适当的太空垫?也许有些方法只是打印回到字符串并检查其长度?
Is there any way (save for doing some hackery with regular expressions which I'd rather not do) to take the escaped string and find out what the printed length is so I can space pad appropriately? Maybe some way to just "print" it back to string and examine the length of that?
推荐答案
这个pyparsing wiki包含这个<对于ANSI转义序列进行匹配,href =http://pyparsing-public.wikispaces.com/Helpful+Expressions#toc7 =noreferrer>有用表达式
The pyparsing wiki includes this helpful expression for matching on ANSI escape sequences:
ESC = Literal('\x1b')
integer = Word(nums)
escapeSeq = Combine(ESC + '[' + Optional(delimitedList(integer,';')) +
oneOf(list(alphas)))
这是如何使它成为一个逃脱序列剥离器:
Here's how to make this into an escape-sequence-stripper:
from pyparsing import *
ESC = Literal('\x1b')
integer = Word(nums)
escapeSeq = Combine(ESC + '[' + Optional(delimitedList(integer,';')) +
oneOf(list(alphas)))
nonAnsiString = lambda s : Suppress(escapeSeq).transformString(s)
unColorString = nonAnsiString('\x1b[1m0.0\x1b[0m')
print unColorString, len(unColorString)
打印:
0.0 3
这篇关于在Python中为ANSI颜色代码的字符串获取正确的字符串长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!