why the result of '1' == u'1' in python2 is True?

Viewed 55

I use python2.7 in Linux. From https://docs.python.org/2/howto/unicode.html. I find that python use one byte for each alphabet in str, while it uses 4 bytes in Unicode string. So why I get True after I input '1' == u'1'.

A similar truth in python2:

    In [1]: a = {}
    In [2]: a['1'] = 1
    In [3]: a[u'1']
    Out[3]: 1
1 Answers

UTF-8 is capable of encoding all 1,112,064 valid character code points in Unicode using one to four one-byte (8-bit) code units. Code points with lower numerical values, which tend to occur more frequently, are encoded using fewer bytes. It was designed for backward compatibility with ASCII: the first 128 characters of Unicode, which correspond one-to-one with ASCII, are encoded using a single byte with the same binary value as ASCII, so that valid ASCII text is valid UTF-8-encoded Unicode as well.

You can see an example of this:

>>> a = u'1'
>>> a.encode('utf-8')
'1'
>>> b = u'ツ'
>>> b.encode('utf-8')
'\xe3\x83\x84'
Related