gpt4 book ai didi

Python str 与 unicode 类型

转载 作者:IT老高 更新时间:2023-10-28 21:08:09 26 4
gpt4 key购买 nike

使用 Python 2.7,我想知道使用类型 unicode 而不是 str 有什么真正的优势,因为它们似乎都能够保持Unicode 字符串。除了能够使用转义字符 \unicode 字符串中设置 Unicode 代码之外,还有什么特殊原因吗?:

执行一个模块:

# -*- coding: utf-8 -*-

a = 'á'
ua = u'á'
print a, ua

结果:á, á

使用 Python shell 进行更多测试:

>>> a = 'á'
>>> a
'\xc3\xa1'
>>> ua = u'á'
>>> ua
u'\xe1'
>>> ua.encode('utf8')
'\xc3\xa1'
>>> ua.encode('latin1')
'\xe1'
>>> ua
u'\xe1'

因此,unicode 字符串似乎是使用 latin1 而不是 utf-8 编码的,而原始字符串是使用 编码的utf-8?我现在更迷茫了! :S

最佳答案

unicode 用于处理 text。文本是一系列代码点可能大于单个字节。文本可以以特定编码编码,以将文本表示为原始字节(例如 utf-8latin-1...)。

注意 unicode 没有编码! python使用的内部表示是一个实现细节,只要能够表示你想要的代码点,你就不必关心它。

相反,Python 2 中的 strbytes 的普通序列。不代表文字!

您可以将 unicode 视为某些文本的一般表示,可以通过多种不同方式将其编码为通过 str 表示的二进制数据序列。

注意:在 Python 3 中,unicode 被重命名为 str,并且有一个新的 bytes 类型用于简单的序列字节。

您可以看到的一些差异:

>>> len(u'à')  # a single code point
1
>>> len('à') # by default utf-8 -> takes two bytes
2
>>> len(u'à'.encode('utf-8'))
2
>>> len(u'à'.encode('latin1')) # in latin1 it takes one byte
1
>>> print u'à'.encode('utf-8') # terminal encoding is utf-8
à
>>> print u'à'.encode('latin1') # it cannot understand the latin1 byte

请注意,使用 str 您可以对特定编码表示的单个字节进行较低级别的控制,而使用 unicode 您只能在代码点进行控制等级。例如你可以这样做:

>>> 'àèìòù'
'\xc3\xa0\xc3\xa8\xc3\xac\xc3\xb2\xc3\xb9'
>>> print 'àèìòù'.replace('\xa8', '')
à�ìòù

以前是有效的 UTF-8,现在不再是。使用 unicode 字符串,您不能以结果字符串不是有效的 unicode 文本的方式进行操作。您可以删除代码点,用不同的代码点替换代码点等,但不能弄乱内部表示。

关于Python str 与 unicode 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18034272/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com