我正在尝试使用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
答案 0 :(得分:1)
您的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')
€
答案 1 :(得分:0)
您可以使用unichr()函数
print unichr(8364)