[英]Python error “ascii codec cannot encode character…”
I have a script which shows 我有一个脚本显示
UnicodeEncodeError: 'ascii' codec can't encode character u'\u044e' in position 0: ordinal not in range(128)
for line print ord(u), u
. 对于行
print ord(u), u
。 How can I run the script ok? 我该如何正常运行脚本?
I run C:\\Python27\\pythonw.exe name.py
. 我运行
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
You cannot print a unicode charater to the windows console if the local encoding doesn't support it. 如果本地编码不支持,则无法在Windows控制台上打印unicode字符。 So python tries to encode it as
ascii
and fails. 因此,python尝试将其编码为
ascii
并失败。 The problematic line is: 有问题的行是:
print ord(u), u
u
is a unicode character. u
是unicode字符。 What you want is probably: 您想要的可能是:
# -*- 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
Also use python.exe
for console applications, not pythonw.exe
也将
python.exe
用于控制台应用程序,而不是pythonw.exe
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.