在Windows環(huán)境下,使用print打印中文時時常會碰到打印不出而報錯的問題秧荆,這個很讓人討厭。其問題的根源在于Python3使用utf8字符串埃仪,打印時遇到GBK無法解碼的就會報錯辰如。我們可以用一種簡單粗暴的方式進行解決。
首先重新寫一個打印函數(shù)贵试,其代碼如下:
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函數(shù)比print函數(shù)多了一個參數(shù)replace,主要是遇到不能轉碼字符時使用replace指定的字符來替代毙玻。