我必须在Python中做什么来找出字符串的编码?
当前回答
这可能会帮助其他人,我开始测试变量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
其他回答
Unicode不是一种编码——引用Kumar McMillan的话:
如果ASCII, UTF-8和其他字节字符串是“text”… ...那么Unicode就是“文本性”; 它是文本的抽象形式
读一读McMillan在PyCon 2008上的Unicode In Python,完全解密的演讲,它比Stack Overflow上的大多数相关答案更好地解释了事情。
在python中3。x所有字符串都是Unicode字符的序列。使用isinstance检查STR(默认为unicode字符串)就足够了。
isinstance(x, str)
关于python 2.x, 大多数人似乎都在使用带有两次检查的if语句。一个用于STR,一个用于unicode。
如果你想检查你是否有一个'string-like'的对象,并且只有一个语句,你可以这样做:
isinstance(x, basestring)
注意,在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
用同样的方法来区分它们。
这可能会帮助其他人,我开始测试变量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的,大多数时候可能有更好的方法。
推荐文章
- Numpy Max vs amax vs maximum
- 我应该在.gitignore文件中添加Django迁移文件吗?
- 每n行有熊猫
- 实例属性attribute_name定义在__init__之外
- 如何获取在Python中捕获的异常的名称?
- 第一次出现的值大于现有值的Numpy
- 如何从Python函数中返回两个值?
- 前一个月的Python日期
- Python中方括号括起来的列表和圆括号括起来的列表有什么区别?
- Python日志记录不输出任何东西
- 每n秒运行特定代码
- SQLAlchemy是否有与Django的get_or_create等价的函数?
- 如何将python datetime转换为字符串,具有可读格式的日期?
- 美丽的汤和提取div及其内容的ID
- 在Python中重置生成器对象