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


当前回答

use:

import six
if isinstance(obj, six.text_type)

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

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

其他回答

use:

import six
if isinstance(obj, six.text_type)

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

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

在Python-3中,我必须理解字符串是否像b='\x7f\x00\x00\x01'或b='127.0.0.1'我的解决方案是这样的:

def get_str(value):
    str_value = str(value)
    
    if str_value.isprintable():
        return str_value

    return '.'.join(['%d' % x for x in value])

对我有用,我希望对有需要的人有用

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

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

如果你的代码需要与Python 2和Python 3兼容,你不能直接使用isinstance(s,bytes)或isinstance(s,unicode)这样的东西,而不将它们包装在try/except或Python版本测试中,因为bytes在Python 2中未定义,unicode在Python 3中未定义。

有一些丑陋的变通办法。一种非常糟糕的方法是比较类型的名称,而不是比较类型本身。这里有一个例子:

# convert bytes (python 3) or unicode (python 2) to str
if str(type(s)) == "<class 'bytes'>":
    # only possible in Python 3
    s = s.decode('ascii')  # or  s = str(s)[2:-1]
elif str(type(s)) == "<type 'unicode'>":
    # only possible in Python 2
    s = str(s)

一个稍微不那么丑陋的解决方法是检查Python版本号,例如:

if sys.version_info >= (3,0,0):
    # for Python 3
    if isinstance(s, bytes):
        s = s.decode('ascii')  # or  s = str(s)[2:-1]
else:
    # for Python 2
    if isinstance(s, unicode):
        s = str(s)

这两个都是非python的,大多数时候可能有更好的方法。

Unicode不是一种编码——引用Kumar McMillan的话:

如果ASCII, UTF-8和其他字节字符串是“text”… ...那么Unicode就是“文本性”; 它是文本的抽象形式

读一读McMillan在PyCon 2008上的Unicode In Python,完全解密的演讲,它比Stack Overflow上的大多数相关答案更好地解释了事情。