Python格式化:对于彩色字符串,使用实际长度

3
我使用Python Fabric为终端输出添加颜色,并使用字符串格式化对齐文本。
颜色会向字符串添加不可见的代码,如何避免破坏格式化输出?
>>> from fabric.colors import red
>>> print '{:->27}'.format('line one')
-------------------line one
>>> print '{:->27}'.format('longer line two')
------------longer line two
>>> print '{:->27}'.format(red('line three'))
--------line three
>>>

正如Hans所说,我们只需要加上+9。
>>> 
>>> print '{:->27}'.format('line one')
-------------------line one
>>> print '{:->27}'.format('longer line two')
------------longer line two
>>> print '{:->36}'.format(red('line three'))
-----------------line three
>>> print '{:->36}'.format(red('and more words'))
-------------and more words
>>> print '{:->36}'.format(red('and more words plus one'))
----and more words plus one
>>>
1个回答

0

由于颜色面料的源代码包含了这个:

def _wrap_with(code):
    def inner(text, bold=False):
        c = code
        if bold:
            c = "1;%s" % c
        return "\033[%sm%s\033[0m" % (c, text)
    return inner

red = _wrap_with('31')

而且你的“第三行”输出的长度比其他行短了9个字符,我猜测red(String)的输出总是包含着9个不可见字符,它们存储在字符串"\033[%sm%s\033[0m"中。

所以要修复你的格式问题,在使用red(String)时,你应该输入:

print '{:->(27+9)}'.format(red('line three'))

替代

print '{:->27}'.format(red('line three'))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接