我必须在Python中做什么来找出字符串的编码?
当前回答
对于py2/py3兼容性,只需使用
进口六 如果isinstance(obj, six.text_type)
其他回答
如何判断一个对象是unicode字符串还是字节字符串
可以使用type或isinstance。
在Python 2中:
>>> type(u'abc') # Python 2 unicode string literal
<type 'unicode'>
>>> type('abc') # Python 2 byte string literal
<type 'str'>
在python2中,str只是一个字节序列。巨蟒不知道 它的编码是。unicode类型是存储文本的更安全的方式。 如果你想了解更多,我推荐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。如果它引发UnicodeDecodeError异常,则它是无效的。
>>> 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)
您可以使用通用编码检测器,但请注意,它只会给您最好的猜测,而不是实际的编码,因为不可能知道字符串“abc”的编码。您将需要在其他地方获取编码信息,例如HTTP协议使用内容类型报头。
注意,在Python 3中,这样说并不公平:
字符串是UTFx的任何x(例如。use UTF8) str是Unicode 字符串是Unicode字符的有序集合
Python的str类型(通常)是Unicode码位序列,其中一些映射到字符。
即使在Python 3上,回答这个问题也不像您想象的那么简单。
测试ascii兼容字符串的一个明显的方法是尝试编码:
"Hello there!".encode("ascii")
#>>> b'Hello there!'
"Hello there... ☃!".encode("ascii")
#>>> Traceback (most recent call last):
#>>> File "", line 4, in <module>
#>>> UnicodeEncodeError: 'ascii' codec can't encode character '\u2603' in position 15: ordinal not in range(128)
这个错误区分了不同的情况。
在Python 3中,甚至有一些字符串包含无效的Unicode代码点:
"Hello there!".encode("utf8")
#>>> b'Hello there!'
"\udcc3".encode("utf8")
#>>> Traceback (most recent call last):
#>>> File "", line 19, in <module>
#>>> UnicodeEncodeError: 'utf-8' codec can't encode character '\udcc3' in position 0: surrogates not allowed
用同样的方法来区分它们。
在python中3。x所有字符串都是Unicode字符的序列。使用isinstance检查STR(默认为unicode字符串)就足够了。
isinstance(x, str)
关于python 2.x, 大多数人似乎都在使用带有两次检查的if语句。一个用于STR,一个用于unicode。
如果你想检查你是否有一个'string-like'的对象,并且只有一个语句,你可以这样做:
isinstance(x, basestring)
一种简单的方法是检查unicode是否是内置函数。如果是,你在python2中,你的字符串将是一个字符串。要确保所有内容都使用unicode,可以执行以下操作:
import builtins
i = 'cats'
if 'unicode' in dir(builtins): # True in python 2, False in 3
i = unicode(i)
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录