Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python escape sequence \N{name} not working as per definition

I am trying to print unicode characters given their name as follows:

# -*- coding: utf-8 -*-
print "\N{SOLIDUS}"
print "\N{BLACK SPADE SUIT}"

However the output I get is not very encouraging.

The escape sequence is printed as is.

ActivePython 2.7.2.5 (ActiveState Software Inc.) based on
Python 2.7.2 (default, Jun 24 2011, 12:21:10) [MSC v.1500 32 bit (Intel)] on
Type "help", "copyright", "credits" or "license" for more information.
>>> # -*- coding: utf-8 -*-
... print "\N{SOLIDUS}"
\N{SOLIDUS}
>>> print "\N{BLACK SPADE SUIT}"
\N{BLACK SPADE SUIT}
>>>

I can however see that another asker has been able to do this successfully.

What's wrong?

like image 387
alok Avatar asked Apr 18 '13 07:04

alok


1 Answers

Those sequences only work in unicode strings, which is the only kind of string Python 3 has. So in Python 2 you need to prefix the string literal with a u.

>>> print "\N{SOLIDUS} \N{BLACK SPADE SUIT}"
\N{SOLIDUS} \N{BLACK SPADE SUIT}
>>> print u"\N{SOLIDUS} \N{BLACK SPADE SUIT}"
/ ♠

Relevant line from the docs:

\N{name} Character named name in the Unicode database (Unicode only)

like image 182
ThiefMaster Avatar answered Sep 20 '22 20:09

ThiefMaster