Unicode basics in python

1,315 views 14 slides Sep 29, 2013
Slide 1
Slide 1 of 14
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14

About This Presentation

No description available for this slideshow.


Slide Content

Unicode
in python

We Cover these now
● Unicode history
● terms clarity (code point,BOM,utf-8,utf-16)
● decoding and encoding in python
● how django handles these?
● helpful python modules to tackle it


Note: BOM is used in utf-16.since, it has multi
bytes character code point

How it came?
Americans came up with (7 bit)ASCII
representation with english only alphabets as a
standard to exchange information.(‘A’ - 65, ’a’ -
97)

Rest of the world came up with their
unaccented english characters ('ä', )in their own
way.(messed up)

What causes unicode born?
To exchange information in all languages, we
got some requirements
●Unique and simple rule was needed
●Adoptable across all machines(windows,ibm,
etc..)
●Efficient storage as much possible

Unicode
Unicode = UCS(universal character set) + bit
representation logic
UCS:
character + code point
(‘a’, 97)
bit representation:
BOM = Big endian (or) Little endian
00 48 00 65 00 6C 00 6C 00 6F (or) 48 00 65 00 6C
00 6C 00 6F 00

utf-8 is famous, because
●multi-byte encoding
●variable width encoding
●upto 4 byte code points are allowed by utf-8
●mostly, No need BOM(8 bits)
●memory efficient
How?
for NON-ASCII bytes,
1st byte is reserved to indicate the no of
bytes the char is using(eg.compression)

decoding
Character to Numeric value(code point)
conversion
●from <type 'str'> to <type 'unicode'>
●it throws maximum “UnicodeDecodeError:”


(samples demo)

encoding
●Numeric value(code point) to Characters
●from <type 'unicode'> to <type 'str'>
●it throws maximum “UnicodeEncodeError:”

(samples demo)

Rules to Remember…
●Decode early, Unicode everywhere, Encode late
●UTF-8 is the best guess for an encoding
●chardet.detect()
==========================

in Python 3 this is solved…

●<type 'str'> is a Unicode object

How django handles?
>>> def to_unicode(
... obj, encoding='utf-8'):
... if isinstance(obj, basestring):
... if not isinstance(obj, unicode):
... obj = unicode(obj, encoding)
... return obj

smart_text(s, encoding='utf-8',
strings_only=False, errors='strict')
force_text(s, encoding='utf-8', strings_only=False,
errors='strict')
smart_bytes(s, encoding='utf-8',
strings_only=False, errors='strict')

Related python modules..
●chardet.detect()
●unicodedata
●codecs

Thanks for your time
Post your questions.

samples demo….

screenshot2