python错误之UnicodeEncodeError: 'ascii' codec can't encode characters in position 78: ordinal not in range(128)

# coding = ascii

import json
import pickle
import sys
import os
  • decode()和encode方法中第一个参数为编码格式,第二个为出现无法转换时使用何种处理方式(ignore:忽略,无法转换则为空;replace:用?代替)
  由于在python3中字符编码默认为unicode,所有直接调用encode方法实现字符编码的转换,由于asscii字符中本来就不包含中文字符,所以decode为他

  会造成报错,是用replace后虽然能比避免报错,但是会再最终解码后造成中文为??的结果

# 字符转码实现
test = "你好"
#获得当前文件编码格式
print(sys.getdefaultencoding())
print(test.encode("utf-8").decode("ascii","replace").encode("ascii","replace").decode("utf-8"))
exec(test)
原文地址:https://www.cnblogs.com/g177w/p/errpy2.html