Python, Unicode, and the Windows console

前端 未结 13 2099
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-21 04:38

When I try to print a Unicode string in a Windows console, I get a UnicodeEncodeError: \'charmap\' codec can\'t encode character .... error. I assume this is b

13条回答
  •  隐瞒了意图╮
    2020-11-21 05:05

    TL;DR:

    print(yourstring.encode('ascii','replace'));
    

    I ran into this myself, working on a Twitch chat (IRC) bot. (Python 2.7 latest)

    I wanted to parse chat messages in order to respond...

    msg = s.recv(1024).decode("utf-8")
    

    but also print them safely to the console in a human-readable format:

    print(msg.encode('ascii','replace'));
    

    This corrected the issue of the bot throwing UnicodeEncodeError: 'charmap' errors and replaced the unicode characters with ?.

提交回复
热议问题