Python, Unicode, and the Windows console

前端 未结 13 2141
佛祖请我去吃肉
佛祖请我去吃肉 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:11

    If you're not interested in getting a reliable representation of the bad character(s) you might use something like this (working with python >= 2.6, including 3.x):

    from __future__ import print_function
    import sys
    
    def safeprint(s):
        try:
            print(s)
        except UnicodeEncodeError:
            if sys.version_info >= (3,):
                print(s.encode('utf8').decode(sys.stdout.encoding))
            else:
                print(s.encode('utf8'))
    
    safeprint(u"\N{EM DASH}")
    

    The bad character(s) in the string will be converted in a representation which is printable by the Windows console.

提交回复
热议问题