2

我有一个脚本显示

UnicodeEncodeError: 'ascii' codec can't encode character u'\u044e' in position 0: ordinal not in range(128)

为线print ord(u), u。我怎样才能正常运行脚本?

我跑C:\Python27\pythonw.exe name.py

# -*- encoding: utf-8 -*-
print "Russian letters".center(18*4)
i = 0
for c in "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ"\
         "абвгдежзийклмнопрстуфхцчшщъыьэюя":
  u = unicode(c, 'koi8-r')  
  print ord(u), u
  i += 1
  if i % 4 == 0:
    print
4

1 回答 1

0

如果本地编码不支持,则无法将 unicode 字符打印到 Windows 控制台。所以 python 尝试将其编码为ascii并失败。有问题的行是:

print ord(u), u

u是一个 Unicode 字符。你想要的可能是:

# -*- encoding: utf-8 -*-

print "Russian letters".center(18*4)
i = 0
for c in u"АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ"\
         u"абвгдежзийклмнопрстуфхцчшщъыьэюя":
    u = c.encode('koi8-r')  
    print ord(u), u
    i += 1
    if i % 4 == 0:
        print

python.exe用于控制台应用程序,而不是pythonw.exe

于 2013-08-11T20:11:19.940 回答