首页 > 解决方案 > 在 Python 3 中,在 encode('utf-8') 之后,可变长度从 2 变为 4

问题描述

我正在将 Python 2 代码转换为 Python 3,并且需要使用 encode() 将 str 转换为字节。

让 str 变量的名称为 s1。

# -*- coding: utf-8 -*-使用*.py 文件的良性设置 unicode 。

在 Python 2 中: type(s1)= <type 'str'>, len(s1)=2;

在 Python 3 中: type(s1)= <class 'str'>, len(s1)=2; type(s1.encode())= <class 'bytes'>,但 len(s1.encode())=4。

此长度更改导致错误:unpack('H', s1.encode()),错误:解包需要 2 个字节的缓冲区

标签: python-3.xunicodeencode

解决方案


推荐阅读