【发布时间】:2021-10-16 06:45:39
【问题描述】:
如何在print() 语句中指定编码?
【问题讨论】:
标签: python python-3.x string encoding
如何在print() 语句中指定编码?
【问题讨论】:
标签: python python-3.x string encoding
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
print() 调用file.write(),file 默认为sys.stdout。 sys.stdout 是一个文件对象,其write() 方法根据其encoding 属性对字符串进行编码。如果您 reconfigure 该属性,它将更改打印时字符串的编码方式:
sys.stdout.reconfigure(encoding='latin-1')
或者,您可以自己对字符串进行编码,然后将字节写入标准输出的底层二进制文件buffer。
sys.stdout.buffer.write("<some text>".encode('latin-1'))
注意buffer 不是公共属性:“这不是 TextIOBase API 的一部分,在某些实现中可能不存在。”
【讨论】: