如何更改 Python 3 中的輸出編碼?

Mary-Kate Olsen
發布: 2024-11-13 10:48:02
原創
350 人瀏覽過

How to Change the Output Encoding in Python 3?

Changing the Output Encoding in Python 3

In Python 2, setting the default output encoding was a straightforward process using sys.stdout = codecs.getwriter("utf-8")(sys.stdout). However, in Python 3, this technique fails because sys.stdout.write() expects a string, while the result of encoding is bytes.

Solution for Python 3.7 and Above

For Python 3.7 and later, the reconfigure() method can be used to modify the encoding of standard streams, including sys.stdout.

sys.stdout.reconfigure(encoding='utf-8')
登入後複製

This will set the encoding for sys.stdout to UTF-8, allowing you to output characters in that encoding.

# Example
sys.stdout.reconfigure(encoding='utf-8')
print("Hello World")  # Output: Hello World
登入後複製

Error Handling

You can also specify how encoding errors are handled by adding an errors parameter to reconfigure(). The following example shows how to handle errors using the replace strategy:

sys.stdout.reconfigure(encoding='utf-8', errors='replace')
登入後複製

With this setting, any Unicode characters that cannot be encoded will be replaced with a specific replacement character (usually a question mark).

以上是如何更改 Python 3 中的輸出編碼?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板