gpt4 book ai didi

unicode - python 3.0,如何使print()输出unicode?

转载 作者:行者123 更新时间:2023-12-03 13:26:13 25 4
gpt4 key购买 nike

我正在WinXP 5.1.2600中工作,编写了一个涉及中文拼音的Python应用程序,这使我陷入了无休止的Unicode问题。切换到Python 3.0已解决了许多问题。但是出于某些奇怪的原因,用于控制台输出的print()函数不支持Unicode。这是一个小程序。

print('sys.stdout encoding is "' + sys.stdout.encoding + '"')
str1 = 'lüelā'
print(str1)


输出为(将尖括号更改为方括号以提高可读性):

    sys.stdout encoding is "cp1252"    Traceback (most recent call last):      File "TestPrintEncoding.py", line 22, in [module]        print(str1)      File "C:\Python30\lib\io.py", line 1491, in write        b = encoder.encode(s)      File "C:\Python30\lib\encodings\cp1252.py", line 19, in encode        return codecs.charmap_encode(input,self.errors,encoding_table)[0]    UnicodeEncodeError: 'charmap' codec can't encode character '\u0101'     in position 4: character maps to [undefined]

Note that ü = \xfc = 252 gives no problem since it's upper ASCII. But ā = \u0101 is beyond 8-bits.

Anyone have an idea how to change the encoding of sys.stdout to 'utf-8'? Bear in mind that Python 3.0 no longer uses the codecs module, if I understand the documentation right.


Apologies, I gave you the program without the preamble. Before the 3 lines given, it starts like this:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys


不幸的是,“ coding:”行指定的编码是源代码的编码,而不是控制台输出的编码。但是谢谢您的想法!

最佳答案

Windows命令提示符(cmd.exe)无法显示您正在使用的Unicode字符,即使Python在内部以正确的方式对其进行了处理。您需要使用IDLE,Cygwin或其他可以正确显示Unicode的程序。

请参阅此线程以获取完整说明:
http://www.nabble.com/unable-to-print-Unicode-characters-in-Python-3-td21670662.html

关于unicode - python 3.0,如何使print()输出unicode?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/507123/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com