python unicode和 utf8字符串比较

时间:2022-06-26 10:35:00
#单个unicode字符串的长度为1, 单个utf-8字符的长度为3
In [3]: u = u"这是一个中文字符串"

In [4]: len(u)
Out[4]: 9

In [5]: utf8str = u.encode("utf-8")

In [6]: len(utf8str)
Out[6]: 27

In [7]: utf8str
Out[7]: '\xe8\xbf\x99\xe6\x98\xaf\xe4\xb8\x80\xe4\xb8\xaa\xe4\xb8\xad\xe6\x96\x8
7\xe5\xad\x97\xe7\xac\xa6\xe4\xb8\xb2'

In [8]: single_utf8str = u"中".encode("utf-8")

In [9]: single_utf8str
Out[9]: '\xe4\xb8\xad'

In [10]: len(single_utf8str)
Out[10]: 3