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.
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
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中文網其他相關文章!