我正在尝试使用 python 打印货币符号。我可以通过规范化 unicode 字符来打印一些货币符号。因为在 python 2.7 中,在字符映射中,我只能看到某些 unicode 字符的映射,而看不到欧元符号“\u20ac”的映射。
要打印欧元符号,我们是否需要在字符映射 python 文件中包含 unicode 字符?
或者我们可以使用其他方式打印欧元符号吗?
我使用下面的代码,但出现以下错误。
输出:
日元
元
欧元
Traceback (most recent call last):
File ".\new-test.py", line 8, in <module>
print list1
File "C:\Python27\lib\encodings\cp437.py", line 12, in encode
return codecs.charmap_encode(input,errors,encoding_map)
UnicodeEncodeError: 'charmap' codec can't encode character u'\u20ac' in position 0: character maps to <undefined>
代码:
from __future__ import unicode_literals
import unicodedata
list = ['Yen','\u00a5','Euro',u'\u20ac']
for character in list:
list1 = (unicodedata.normalize("NFKD", character)).strip()
print list1
最佳答案
您的 Windows 命令提示符配置为使用代码页 437 (cp437
),并且该编码中未定义欧元符号。您可以将代码页更改为1252,它支持以下字符:
C:\>py -2
Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:19:30) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print u'\u20ac'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "D:\dev\Python27\lib\encodings\cp437.py", line 12, in encode
return codecs.charmap_encode(input,errors,encoding_map)
UnicodeEncodeError: 'charmap' codec can't encode character u'\u20ac' in position 0: character maps to <undefined>
>>> ^Z
C:\>chcp 1252
Active code page: 1252
C:\>py -2
Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:19:30) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print u'\u20ac'
€
更好的选择是切换到 Python 3.6 或更高版本,它使用 Windows Unicode API 直接写入控制台,绕过编码问题:
C:\>py -3
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print('\u20ac')
€
关于python - 使用 python 模块通过转换 unicode 字符 u'\u20ac' 打印欧元符号 €,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53083987/