Home > Article > Backend Development > How to Change 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.
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).
The above is the detailed content of How to Change the Output Encoding in Python 3?. For more information, please follow other related articles on the PHP Chinese website!