简体   繁体   English

Python错误“ ASCII编解码器无法编码字符…”

[英]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.

相关问题 Python错误:UnicodeEncodeError:'ascii'编解码器无法编码字符 - Python error : UnicodeEncodeError: 'ascii' codec can't encode character Python Unicode错误,“ ascii”编解码器无法编码字符 - Python Unicode error, 'ascii' codec can't encode character python'ascii'编解码器无法编码字符 - python 'ascii' codec can't encode character 'ascii'编解码器无法编码字符错误 - 'ascii' codec can't encode character error Bioformats-Python错误:'ascii'编解码器在使用OMEXML()时无法对字符u'\ xb5'进行编码 - Bioformats-Python error: 'ascii' codec can't encode character u'\xb5' when using OMEXML() Python错误; UnicodeEncodeError:'ascii'编解码器无法编码字符u'\ u2026' - Python Error; UnicodeEncodeError: 'ascii' codec can't encode character u'\u2026' Python unicode错误。 UnicodeEncodeError:'ascii'编解码器无法编码字符u'\\ u4e3a' - Python unicode error. UnicodeEncodeError: 'ascii' codec can't encode character u'\u4e3a' Python ASCII 编解码器在写入 CSV 期间无法编码字符错误 - Python ASCII codec can't encode character error during write to CSV 收到UnicodeEncodeError的Python脚本:“ ascii”编解码器无法编码字符 - Python script receiving a UnicodeEncodeError: 'ascii' codec can't encode character Python,Docker - “ascii”编解码器无法编码字符 - Python, Docker - 'ascii' codec can't encode character
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM