如何检查字符串是unicode还是ascii?

2024-03-28 09:46:13 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
3条回答

在Python 3中,所有字符串都是Unicode字符序列。有一个保存原始字节的bytes类型。

在Python 2中,字符串可以是str类型或unicode类型。你可以通过这样的代码来判断:

def whatisthis(s):
    if isinstance(s, str):
        print "ordinary string"
    elif isinstance(s, unicode):
        print "unicode string"
    else:
        print "not a string"

这并不区分“Unicode或ASCII”;它只区分Python类型。Unicode字符串可以由ASCII范围内的纯字符组成,bytestring可以包含ASCII、编码的Unicode甚至非文本数据。

在Python3.x中,所有字符串都是Unicode字符序列。对str执行isinstance检查(默认情况下是unicode字符串)就足够了。

isinstance(x, str)

关于Python2.x, 大多数人似乎在使用一个if语句,它有两个检查项。一个用于str,一个用于unicode。

如果要检查是否有一个“string-like”对象,所有对象都有一个语句,则可以执行以下操作:

isinstance(x, basestring)

如何判断对象是unicode字符串还是字节字符串

您可以使用typeisinstance

在Python 2中:

>>> type(u'abc')  # Python 2 unicode string literal
<type 'unicode'>
>>> type('abc')   # Python 2 byte string literal
<type 'str'>

在Python 2中,str只是一个字节序列。Python不知道 它的编码是。类型是存储文本的更安全的方式。 如果你想了解更多,我建议http://farmdev.com/talks/unicode/

在Python 3中:

>>> type('abc')   # Python 3 unicode string literal
<class 'str'>
>>> type(b'abc')  # Python 3 byte string literal
<class 'bytes'>

在Python 3中,str类似于Python 2的unicode,并用于 存储文本。在Python 2中被称为str的内容在Python 3中被称为bytes


如何判断字节字符串是有效的utf-8还是ascii

您可以调用decode。如果引发unicodedecoderror异常,则它无效。

>>> 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)

相关问题 更多 >