Skip to main content
 首页 » 编程设计

python之再次出现在 Python 中的非 ascii 字符

2025年05月04日10lautakyan007

如何成功地将非 ASCII 字符添加到 Python 源代码中?

例如:

a = "ű"- 匈牙利字母

--------Sample------ 
#-*- coding: iso8859_2 -*- 
a = "ű" 
print "ű" 
--------------------- 
output = √    

根据需要不是 ű。

请您参考如下方法:

看起来您正在美国 Windows 控制台上使用 Python。我这样说是因为您实际收到的字符是您打印的 iso8859_2 字符的 cp437 编码字符。不幸的是,cp437 不支持 ű。如果您想查看该字符,则不能使用美国 Windows 控制台。使用 Idle 或 Pythonwin。

您还应该使用 Unicode 字符串。当您使用 coding: iso8859_2 时,您是在声明“此源文件中的字符是使用 ISO 8859-2 转换表编码到磁盘的”。如果您点击该链接,您会发现值 251 代表 ű。如果将相同的字节值写入 cp437终端,你会得到一个平方根符号。对于 Unicode 字符串,Python 会将字节 251 转换为 Unicode。字符 U+0171,它唯一标识字符 LATIN SMALL LETTER LETTER WITH DOUBLE ACUTE。打印到终端时,如果可能,Python 会将 Unicode 字符转换为终端编码,或者抛出错误而不是为不受支持的字符写入垃圾。

例子

# coding: iso8859_2 
import unicodedata as ud 
s = 'ű' 
u = u'ű' 
print 'ISO 8859-2 value:',ord(s) 
print 'Unicode value:   ',ord(u) 
print 'Unicode name:    ',ud.name(u) 
print 'Unicode name of cp437 value %d: %s' % (ord(s),ud.name(s.decode('cp437'))) 
 
print s 
print u 

输出

ISO 8859-2 value: 251 
Unicode value:    U+0171 
Unicode name:     LATIN SMALL LETTER U WITH DOUBLE ACUTE 
Unicode name of cp437 value 251: SQUARE ROOT 
√ 
Traceback (most recent call last): 
  File "C:\ex.py", line 11, in <module> 
    print u 
  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'\u0171' in position 0: character maps to <undefined> 

因此您看到字节字符串打印了不正确的平方根符号 (√),而 Unicode 字符串正确显示该字符不受支持。