【问题标题】:How do I specify the encoding in an print() statement? [duplicate]如何在 print() 语句中指定编码? [复制]
【发布时间】:2021-10-16 06:45:39
【问题描述】:

如何在print() 语句中指定编码?

【问题讨论】:

    标签: python python-3.x string encoding


    【解决方案1】:
    print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
    

    print() 调用file.write()file 默认为sys.stdoutsys.stdout 是一个文件对象,其write() 方法根据其encoding 属性对字符串进行编码。如果您 reconfigure 该属性,它将更改打印时字符串的编码方式:

    sys.stdout.reconfigure(encoding='latin-1')
    

    或者,您可以自己对字符串进行编码,然后将字节写入标准输出的底层二进制文件buffer

    sys.stdout.buffer.write("<some text>".encode('latin-1'))
    

    注意buffer 不是公共属性:“这不是 TextIOBase API 的一部分,在某些实现中可能不存在。”

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-24
      • 2022-01-21
      • 1970-01-01
      • 2016-12-29
      • 2010-12-25
      • 2019-10-04
      相关资源
      最近更新 更多