使用 python 模块打印欧元符号 € 通过转换 unicode 字符 u'\u20ac'



我正在尝试使用python打印货币符号。我可以通过规范unicode字符来打印一些货币符号。因为在python 2.7中,在字符映射中,我只能看到一些unicode字符的映射,而不能看到'\u20ac'的EURO符号的映射。

要打印EURO符号,我们需要在字符映射python文件中包含unicode字符吗?

或者,我们有没有其他方法可以用来打印欧元符号?

我使用了下面的代码,我得到了下面的错误。

输出:

日元

¥

欧元

Traceback (most recent call last):
File ".new-test.py", line 8, in <module>
print list1
File "C:Python27libencodingscp437.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:devPython27libencodingscp437.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')
€

您可以使用unichr((函数

print unichr(8364)

最新更新