>>> u_umlaut = b'\xc3\x9c' # UTF-8 representation of the letter 'Ü'
>>> u_umlaut.decode('utf-8')
u'\xdc'
>>> u_umlaut.decode('ascii')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)
在Python 3中,所有字符串都是Unicode字符序列。有一个保存原始字节的
bytes
类型。在Python 2中,字符串可以是
str
类型或unicode
类型。你可以通过这样的代码来判断:这并不区分“Unicode或ASCII”;它只区分Python类型。Unicode字符串可以由ASCII范围内的纯字符组成,bytestring可以包含ASCII、编码的Unicode甚至非文本数据。
在Python3.x中,所有字符串都是Unicode字符序列。对str执行isinstance检查(默认情况下是unicode字符串)就足够了。
关于Python2.x, 大多数人似乎在使用一个if语句,它有两个检查项。一个用于str,一个用于unicode。
如果要检查是否有一个“string-like”对象,所有对象都有一个语句,则可以执行以下操作:
如何判断对象是unicode字符串还是字节字符串
您可以使用
type
或isinstance
。在Python 2中:
在Python 2中,
str
只是一个字节序列。Python不知道 它的编码是。类型是存储文本的更安全的方式。 如果你想了解更多,我建议http://farmdev.com/talks/unicode/。在Python 3中:
在Python 3中,
str
类似于Python 2的unicode
,并用于 存储文本。在Python 2中被称为str
的内容在Python 3中被称为bytes
。如何判断字节字符串是有效的utf-8还是ascii
您可以调用
decode
。如果引发unicodedecoderror异常,则它无效。相关问题 更多 >
编程相关推荐