1

The topic seems to have been discussed to death on SO, still I can't for the life of me manage to render a simple string with ANSI color characters. Obviously the following works fine, the site name appears in green on my terminal:

>>> print u'I love \u001b[0;32mStack Overflow\u001b[0m'
I love Stack Overflow

However:

>>> test='I love \u001b[0;32mStack Overflow\u001b[0m'

>>> test
'I love \\u001b[0;32mStack Overflow\\u001b[0m'

>>> print test
I love \u001b[0;32mStack Overflow\u001b[0m

>>> print test.encode('utf8')
I love \u001b[0;32mStack Overflow\u001b[0m

>>> print test.decode('utf8')
I love \u001b[0;32mStack Overflow\u001b[0m

>>> print unicode(test, 'utf8')
I love \u001b[0;32mStack Overflow\u001b[0m

What the hell?

chris_here
  • 11
  • 3

2 Answers2

1

Define it as a Unicode string:

 test = u'I love \u001b[0;32mStack Overflow\u001b[0m'

This way it will print correctly:

>>> print test
I love Stack Overflow
adrianus
  • 3,141
  • 1
  • 22
  • 41
  • I would if I could but I can't. I get the variable as is. – chris_here Feb 17 '16 at 14:56
  • @chris_here: do you understand the difference between `u'\u0021'` and `u'\\u0021'`? Update your question and include the *actual* value (run `print repr(your_variable)`). – jfs Feb 17 '16 at 20:06
1

If you are receiving Unicode escapes in byte string, decode it:

>>> test='I love \u001b[0;32mStack Overflow\u001b[0m'
>>> test
'I love \\u001b[0;32mStack Overflow\\u001b[0m'
>>> test.decode('unicode_escape')
u'I love \x1b[0;32mStack Overflow\x1b[0m'
>>> print(test.decode('unicode_escape'))
I love Stack Overflow
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
  • Ok that's exactly what I was after, thanks a lot. I think the confusion stemmed from the fact that using ASCII chars \033 or \x1b works readily but \u001b does not. – chris_here Feb 18 '16 at 13:08
  • If you get a byte string with the individual characters for \033 or \x1b (4 bytes each) you'd still have to decode them, though. – Mark Tolonen Feb 18 '16 at 15:39