admin管理员组文章数量:1610852
python 字符转码异常
使用代码:
str(row[2], encoding=charset)
使用场景
从数据库中取字段,但字段存储的中文编码格式不一致
当执行时,遇到错误:UnicodeDecodeError: 'gb2312' codec can't decode byte 0x93 in position 4: illegal multibyte sequence
这是转码失败!
解决方式
def __init__(self, value='', encoding=None, errors='strict'): # known special case of str.__init__
"""
str(object='') -> str
str(bytes_or_buffer[, encoding[, errors]]) -> str
Create a new string object from the given object. If encoding or
errors is specified, then the object must expose a data buffer
that will be decoded using the given encoding and error handler.
Otherwise, returns the result of object.__str__() (if defined)
or repr(object).
encoding defaults to sys.getdefaultencoding().
errors defaults to 'strict'.
# (copied from class doc)
"""
pass
str(row[2], encoding=charset, errors='ignore') 增加参数ignore
还有一种方式 decode(‘gb2312’,‘ignore’)
后语
网上还有一种方式是,将gb2312改为gbk,认为gb2312的编码集没有gbk广泛。但我这里不完全适用,gbk的编码也会偶尔报错
本文标签: DecodebyteCodecUnicodeDecodeErrormultibyte
版权声明:本文标题:UnicodeDecodeError: ‘gb2312‘ codec can‘t decode byte 0x93 in position 4: illegal multibyte sequence 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://www.elefans.com/dianzi/1728606026a1165464.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论