Escape sequences (colour) and padding with "%8s"%
Tim Chase
python.list at tim.thechases.com
Wed Aug 9 15:04:26 EDT 2006
> I used escape sequences to produce colour output, but a construct like
>
> print "%8s" % str_with_escape
>
> doesn't do the right thing. I suppose the padding counts the escape
> characters, too.
>
> What could be a solution?
You omit half of the equation: the contents of str_with_escape.
>>> print "hello %c[1mworld%c[0m" % (27, 27)
works just fine for me in Linux (it chokes a bit on Win32 under
cmd.exe, printing the actual escape character, rather than
interpreting it as an ANSI control sequence).
One can even do fancy stuff like:
>>> mapping = {'bold': '\x1b[1m', 'normal':'\x1b[0m',
'blue':'\x1b[34m'}
>>> print "this has some %(bold)sbold%(normal)s text and some
%(blue)sblue%(normal)s text and some %(bold)s%(blue)stext that is
bold and blue%(normal)s in it" % mapping
and it works with %8s as well.
You might prefer to use the standard curses library rather than
try and roll your own...
-tkc
More information about the Python-list
mailing list