繁体   English   中英

python3 TypeError:需要一个类似字节的对象,而不是'str' html

[英]python3 TypeError: a bytes-like object is required, not 'str' html

下面的代码在python2.7中完美运行

for thepkg in mypkgs.get('package'):
    pkgname = thepkg.get('name').encode('utf-8').replace(' ', '_')
    print('                             <option value="'+pkgname+'">'+pkgname+'</option>')

但是在python3中它抛出了错误

    pkgname = thepkg.get('name').encode('utf-8').replace(' ', '_')
TypeError: a bytes-like object is required, not 'str'

我尝试了各种变体,但是当 pkg.get('name') 值是非英语字符串(例如日语或中文名称)时,会弹出不同的错误或无法正确显示呈现的 HTML 页面。 它再次在 python2.7 上的 HTML 中完美运行

该问题是由 sys.stdout.encoding 在 HTML 上设置为 ANSI_X3.4-1968 当我将编码重置为 utf-8 时使用

sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding = 'utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.detach(), encoding = 'utf-8')

在 print() 之前,HTML 中的字符开始正常显示

我也不需要使用 .encode('utf-8') 因为默认情况下 thepkg.get('name') 是一个 unicode 字符串

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM