User
Resources to help you learn how to handle Unicode in your Python programs:
General Unicode Resources
Python-Specific Resources
Standard Reference
- unichr builtin
- string handling — example: u'Hello\u0020World !'
- unicodedata module
- regular expressions — see the (?u) flag, and the re.UNICODE constant
- exceptions — UnicodeEncodeError
Tutorials
- End to End Unicode Web Applications in Python
- Dive Into Python: Unicode
- Python and Unicode (pdf talk) He also has a brief tutorial.
- Unicode for Programmers — Java and Python info
- Python Unicode Objects — brief notes
Sample Code
Pitfalls
- StrIsNotAString
- PrintFails
- ShellRedirectionFails
- UnicodeEncodeError
- UnicodeDecodeError
- DefaultEncoding
- The standard encodings list is for the current version of python. GB2312 (PRC Chinese,) for example, is in Python2.4, but not in Python2.2, nor Python2.3.
Supported Encodings
Encodings can be registered at runtime, as well, with the codecs module.
Python2.4 supports many codecs that 2.2 and 2.3 do not, including Chinese bg2312.
Encodings are specified in files found in a directory called «encodings»; one way to find the encodings with your Python distribution is to check the contents of this directory:
>>> import encodings, os >>> [n for n in os.listdir(os.path.dirname(encodings.__file__)) . if n[0] != '_' and n.endswith('.py')] ['aliases.py', 'ascii.py', 'base64_codec.py', 'charmap.py', 'cp037.py', . ]
Another is to list aliases from the encodings module.
>>> import encodings >>> from encodings import aliases >>> aliases.aliases
«The Truth about Unicode in Python»
Discussion
Here’s a conversation that I had on CommunityWiki; I’d like to bring the main ideas into here.
Conversation between Lion and Bayle
That looks like 32-bits per character, so I’d say it’s some form of little-endian utf-32.
And for some strange reason, Python only comes with «utf-8» and «utf-16» as valid «decode» values.
1 >>> bytes = "H\x00i\x00\n\x00" 2 >>> unistring = bytes.decode('utf-16') 3 >>> print unistring 4 u'Hi\n'
You can do that for either «utf-8» or «utf-16.» But for some reason, I can’t say «utf-32» or «utf-32LE» (LE=little endian). I have no idea why. I also don’t know how it is that my Python programs are producing UTF-32 for you.
I’ve been wanting to diagram how Python unicode works, like how I diagrammed it’s time use, and regex use.
Basically, «encode» is meant to be called from unicode data, and «decode» is meant to be called from bytes data. Continuing from above:
1 >>> bytes 2 'H\x00i\x00\n\x00' 3 >>> unistring = bytes.decode('utf-16') 4 >>> unistring 5 u'Hi\n' 6 >>> unistring.encode('utf-8') 7 'Hi\n' 8 >>> unistring.encode('utf-16') 9 '\xff\xfeH\x00i\x00\n\x00' 10 >>> unistring.encode('utf-32') 11 Traceback (most recent call last): 12 File " ", line 1, in ? 13 LookupError: unknown encoding: utf-32
I’m guessing that the «\xff» at the beginning of the utf-16 encoding is a byte-order marker, saying «this is little endian.»
I learned about unicode stuff about 2-3 weeks ago. I kept notes about what I thought were the largest mental misconceptions, and what were the most revealing ways of thinking about it. Sadly, I’ve forgotten about all that. (Should’a documented it in the wiki!)
In Python, the data in a unicode or byte string is exactly the same. The difference is only in how Python treats and presents the data. I found it super-helpful to not think about what the console said, or work with the console, because the console lies. That is, the characters go through conversions even being printed to the screen: Your console has an understanding of encoding, and your fonts have an understanding of encoding, and I had a lot of difficulty seperating it out.
I had a lot easier time thinking about the concepts, instead of the concrete representations. (Which is opposite my usual course of thinking.)
«Decoded,» to Python’s mind, is data being treated as unicode data. «Encoded,» to Python’s mind, is data being treated as bytes. The data isn’t actually changing form, at all. It’s just the treatment of the same data that is being changed. But there is no actual conversion taking place.
So, you only ever run «decode» on a byte string. (Another thing: Don’t think of native Python strings as «strings.» Think of them as «bytes.» And indeed: In the new Python 3.0, they’re calling it just that: strings are called «bytes» in Python3, and unicode strings are called just «strings» in Python3.)
So you can decode bytes, and encode unicode strings.
Don’t think about decoding unicode strings, and don’t think about encoding bytes. The bytes are already coded. Only unicode strings live in pure, abstract, heavenly, platonic form. There is no code there, only perfect clarity. (At least, that’s how Python makes it seem for you.)
Again, sadly, I have no idea how to get from UTF-32 to Python unicode. I don’t see the path. I saw something somewhere about being able to compile something in to your Python.
That said, if I’m actually serving UTF-32 to you somehow. . then there’s probably a way I just don’t know.
(Discussion continued)
On side-notes, I think the diagrams I’ve posted for WorkingWithTime and RegularExpressions were eaten up in the transition to MoinMoin 1.3; I’ll repost them soon, after I get my own wiki upgraded to 1.3.
Unicode (last edited 2008-11-15 14:00:16 by localhost )
unichr Python
Возвращает Юникод строку из одного символа чей Юникод номер это переданное целое число i.
Например, unichr(97) возвращает u’a’. Является обратной функцией функции ord() для строк в формате Юникод.
Область допустимых аргументов зависит от того как настроен Python – может быть как UCS2 [0..0xFFFF] так и UCS4 [0..0x10FFFF]. ValueError поднимается в случае если аргумент невалидный. Для ASCII и 8-bit строк используется chr() .
Пример
Как уже был сказано выше в Python 3 нет функции unichr, используется функция chr() ниже код для Python 2
# Python 2 for i in range ( 128 ): print ( «unichr(): » .format(counter=i, value= unichr (i)))
python2 unichr_ex.py unichr(0): unichr(1): unichr(2): unichr(3): unichr(4): unichr(5): unichr(6): unichr(7): unichr(8): unichr(9): unichr(10): unichr(11): unichr(12): unichr(13): unichr(14): unichr(15): unichr(16): unichr(17): unichr(18): unichr(19): unichr(20): unichr(21): unichr(22): unichr(23): unichr(24): unichr(25): unichr(26): � unichr(27): nichr(28): unichr(29): unichr(30): unichr(31): unichr(32): unichr(33): ! unichr(34): » unichr(35): # unichr(36): $ unichr(37): % unichr(38): & unichr(39): ‘ unichr(40): ( unichr(41): ) unichr(42): * unichr(43): + unichr(44): , unichr(45): — unichr(46): . unichr(47): / unichr(48): 0 unichr(49): 1 unichr(50): 2 unichr(51): 3 unichr(52): 4 unichr(53): 5 unichr(54): 6 unichr(55): 7 unichr(56): 8 unichr(57): 9 unichr(58): : unichr(59): ; unichr(60): < unichr(61): = unichr(62): >unichr(63): ? unichr(64): @ unichr(65): A unichr(66): B unichr(67): C unichr(68): D unichr(69): E unichr(70): F unichr(71): G unichr(72): H unichr(73): I unichr(74): J unichr(75): K unichr(76): L unichr(77): M unichr(78): N unichr(79): O unichr(80): P unichr(81): Q unichr(82): R unichr(83): S unichr(84): T unichr(85): U unichr(86): V unichr(87): W unichr(88): X unichr(89): Y unichr(90): Z unichr(91): [ unichr(92): \ unichr(93): ] unichr(94): ^ unichr(95): _ unichr(96): ` unichr(97): a unichr(98): b unichr(99): c unichr(100): d unichr(101): e unichr(102): f unichr(103): g unichr(104): h unichr(105): i unichr(106): j unichr(107): k unichr(108): l unichr(109): m unichr(110): n unichr(111): o unichr(112): p unichr(113): q unichr(114): r unichr(115): s unichr(116): t unichr(117): u unichr(118): v unichr(119): w unichr(120): x unichr(121): y unichr(122): z unichr(123): < unichr(124): | unichr(125): >unichr(126): ~ unichr(127):
chr Python
chr(0): ^ @ chr(1): ^ A chr(2): ^ B chr(3): ^ C chr(4): ^ D chr(5): ^ E chr(6): ^ F chr(7): ^ G chr(8): ^ H chr(9): chr(10): chr(11): ^ K chr(12): ^ L chr(13): ^ M chr(14): ^ N chr(15): ^ O chr(16): ^ P chr(17): ^ Q chr(18): ^ R chr(19): ^ S chr(20): ^ T chr(21): ^ U chr(22): ^ V chr(23): ^ W chr(24): ^ X chr(25): ^ Y chr(26): ^ Z chr(27): ^ [ chr(28): ^ \ chr(29): ^ ] chr(30): ^ ^ chr(31): ^ _ chr(32): chr(33): ! chr(34): » chr(35): # chr(36): $ chr(37): % chr(38): & chr(39): ‘ chr(40): ( chr(41): ) chr(42): * chr(43): + chr(44): , chr(45): — chr(46): . chr(47): / chr(48): 0 chr(49): 1 chr(50): 2 chr(51): 3 chr(52): 4 chr(53): 5 chr(54): 6 chr(55): 7 chr(56): 8 chr(57): 9 chr(58): : chr(59): ; chr(60): < chr(61): = chr(62): >chr(63): ? chr(64): @ chr(65): A chr(66): B chr(67): C chr(68): D chr(69): E chr(70): F chr(71): G chr(72): H chr(73): I chr(74): J chr(75): K chr(76): L chr(77): M chr(78): N chr(79): O chr(80): P chr(81): Q chr(82): R chr(83): S chr(84): T chr(85): U chr(86): V chr(87): W chr(88): X chr(89): Y chr(90): Z chr(91): [ chr(92): \ chr(93): ] chr(94): ^ chr(95): _ chr(96): ` chr(97): a chr(98): b chr(99): c chr(100): d chr(101): e chr(102): f chr(103): g chr(104): h chr(105): i chr(106): j chr(107): k chr(108): l chr(109): m chr(110): n chr(111): o chr(112): p chr(113): q chr(114): r chr(115): s chr(116): t chr(117): u chr(118): v chr(119): w chr(120): x chr(121): y chr(122): z chr(123): < chr(124): | chr(125): >chr(126): ~ chr(127): ^ ?
Универсальный вариант, который будет работать и в Python 3 и в Python 2
# Python 3 and Python 2 try : get_char = unichr except NameError : get_char = chr for i in range ( 128 ): print ( «character (): » .format(counter=i, value=get_char(i)))
Результат одинаков для Python 2 и 3
python2 chr_unichr.py > python2.txt python3 chr_unichr.py > python3.txt diff python2.txt python3.txt