Home > Backend Development > Python Tutorial > How Can I Properly Display Unicode Characters in the Windows Console?

How Can I Properly Display Unicode Characters in the Windows Console?

Mary-Kate Olsen
Release: 2024-12-19 18:25:14
Original
659 people have browsed it

How Can I Properly Display Unicode Characters in the Windows Console?

Unicode Representation in the Windows Console

When attempting to print strings in the Windows console, developers may encounter the error "UnicodeEncodeError: 'charmap' codec can't encode character." This issue arises from the console's inability to handle certain Unicode characters.

Workarounds:

Python 3.6 and Later:

  • Python 3.6 implemented PEP 528, switching the default console encoding to UTF-8. This allows Unicode characters to be displayed directly without the need for workarounds.

Python 3.5 and Earlier:

  • Win-Unicode-Console: Install the win-unicode-console package, which enables Unicode support in the console.
  • WriteConsoleW() API: Use the WriteConsoleW() API to print Unicode strings directly to the console.
  • PYTHONIOENCODING: Set the PYTHONIOENCODING environment variable to ":replace" to replace unencodable characters with the "?" character.

Setting PYTHONIOENCODING:

set PYTHONIOENCODING=:replace
Copy after login

Replacing Characters:

If replacing unencodable characters with "?" is sufficient, you can use the following:

print(u'[\N{EURO SIGN}]')  # Replaces the Euro sign with "?"
Copy after login

Note:

In Python 3.6 , PYTHONIOENCODING is ignored for interactive console buffers unless PYTHONLEGACYWINDOWSIOENCODING is set to a non-empty string.

The above is the detailed content of How Can I Properly Display Unicode Characters in the Windows Console?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template