chris_here
chris_here

Reputation: 11

Printing color characters in string variable with Python 2.7

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?

Upvotes: 1

Views: 2372

Answers (2)

Mark Tolonen
Mark Tolonen

Reputation: 177481

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

Upvotes: 1

adrianus
adrianus

Reputation: 3199

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

Upvotes: 1

Related Questions