解决在Windows使用print报错的问题

作者: 远飞的大雁2010 | 来源:发表于2016-09-29 17:02 被阅读135次

    在Windows环境下,使用print打印中文时时常会碰到打印不出而报错的问题,这个很让人讨厌。其问题的根源在于Python3使用utf8字符串,打印时遇到GBK无法解码的就会报错。我们可以用一种简单粗暴的方式进行解决。

    首先重新写一个打印函数,其代码如下:

    
    def fprint(*args,sep=' ',end='\n',replace='',**kw):
        '''force print, used in Windows,解决打印GBK问题
        其中replace是遇无法打印字符的替代字符'''
        try:
            print(*args,sep=sep,end=end,**kw)
        except UnicodeEncodeError:
            s = sep.join(str(x) for x in args)
            for c in s:
                try:
                    print(c,end='')
                except UnicodeEncodeError:
                    print(replace, end='')
            print(end,end='')
    

    然后在使用fprint来替代print即可。fprint函数比print函数多了一个参数replace,主要是遇到不能转码字符时使用replace指定的字符来替代。

    相关文章

      网友评论

        本文标题:解决在Windows使用print报错的问题

        本文链接:https://www.haomeiwen.com/subject/sxflyttx.html