我必须在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,甚至是非文本数据。
其他回答
Unicode不是一种编码——引用Kumar McMillan的话:
如果ASCII, UTF-8和其他字节字符串是“text”… ...那么Unicode就是“文本性”; 它是文本的抽象形式
读一读McMillan在PyCon 2008上的Unicode In Python,完全解密的演讲,它比Stack Overflow上的大多数相关答案更好地解释了事情。
这可能会帮助其他人,我开始测试变量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
如果你的代码需要与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的,大多数时候可能有更好的方法。
对于py2/py3兼容性,只需使用
进口六 如果isinstance(obj, six.text_type)
use:
import six
if isinstance(obj, six.text_type)
在六个库中,它被表示为:
if PY3:
string_types = str,
else:
string_types = basestring,
推荐文章
- 在python中,年龄从出生日期开始
- 使用pip安装SciPy
- 在Python中,我应该如何测试变量是否为None, True或False
- 如何在Python中从毫秒创建datetime ?
- 如何解窝(爆炸)在一个熊猫数据帧列,成多行
- 如何使用pip安装opencv ?
- 在pip冻结命令的输出中“pkg-resources==0.0.0”是什么
- 格式y轴为百分比
- 使用Javascript的atob解码base64不能正确解码utf-8字符串
- 熊猫连接问题:列重叠但没有指定后缀
- 为什么空字典在Python中是一个危险的默认值?
- 在Python中,冒号等于(:=)是什么意思?
- Python "SyntaxError:文件中的非ascii字符'\xe2' "
- 如何从psycopg2游标获得列名列表?
- Python中dict对象的联合