UnicodeDecodeError: ‘gb2312‘ codec can‘t decode byte 0x93 in position 4: illegal multibyte sequence

在处理数据库中文字段时,由于编码格式不一致,可能会遇到UnicodeDecodeError。例如,尝试用gb2312解码时,遇到非法的多字节序列。解决方案是在转码时加入`errors='ignore'`或使用`decode('gb2312', 'ignore')`忽略错误。然而,将gb2312改为gbk并不总是有效,因为gbk编码并非万能。针对这种情况,需要正确识别数据的原始编码并适当地进行转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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的编码也会偶尔报错

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值