我必须在Python中做什么来找出字符串的编码?


当前回答

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

在python2中,字符串的类型可以是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范围内的纯字符组成,字节字符串可以包含ASCII、编码的Unicode,甚至是非文本数据。

其他回答

对于py2/py3兼容性,只需使用

进口六 如果isinstance(obj, six.text_type)

您可以使用通用编码检测器,但请注意,它只会给您最好的猜测,而不是实际的编码,因为不可能知道字符串“abc”的编码。您将需要在其他地方获取编码信息,例如HTTP协议使用内容类型报头。

use:

import six
if isinstance(obj, six.text_type)

在六个库中,它被表示为:

if PY3:
    string_types = str,
else:
    string_types = basestring,

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

在python2中,字符串的类型可以是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范围内的纯字符组成,字节字符串可以包含ASCII、编码的Unicode,甚至是非文本数据。

这可能会帮助其他人,我开始测试变量s的字符串类型,但对于我的应用程序,更有意义的是简单地返回s为utf-8。调用return_utf的进程知道它在处理什么,并可以适当地处理字符串。代码不是原始的,但我希望它是Python版本不可知的,不需要版本测试或导入六个版本。请对下面的示例代码进行改进,以帮助其他人。

def return_utf(s):
    if isinstance(s, str):
        return s.encode('utf-8')
    if isinstance(s, (int, float, complex)):
        return str(s).encode('utf-8')
    try:
        return s.encode('utf-8')
    except TypeError:
        try:
            return str(s).encode('utf-8')
        except AttributeError:
            return s
    except AttributeError:
        return s
    return s # assume it was already utf-8