在 Python 代码中,遇到 UnicodeDecodeError: 'ascii' codec can't decode byte 0xe7 in position 1: ordinal not in range(128) 错误,通常是因为字符串中包含非 ASCII 字符。

例如:

data_str += ' 
 ' + key[3] + ': ' + key[0] + ' ' + key[1] + ' 系统: ' + key[2] + '
' 
                        + u"\t发现Badjs:  <font color='warning'>{badjs}</font>  覆盖URL:  <font color='warning'>{\"url\"}
                          </font>  发现Crash:  <font color='warning'>{crash}</font>  ANR:  <font color='warning'>{anr}</font>
".format(
                badjs=str(device_data[key]['badjs']), url=str(device_data[key]['url']),
                crash=str(device_data[key]['crash']), anr=str(device_data[key]['anr']))

这个错误表示 Python 解释器尝试使用 ASCII 编码来解码字符串,但字符串中包含了非 ASCII 字符,导致解码失败。

解决方法:

  1. 将字符串声明为 Unicode 字符串,在字符串前面加上 u。
data_str += u' 
 ' + key[3] + ': ' + key[0] + ' ' + key[1] + u' 系统: ' + key[2] + u'
' 
                        + u"\t发现Badjs:  <font color='warning'>{badjs}</font>  覆盖URL:  <font color='warning'>{\"url\"}
                          </font>  发现Crash:  <font color='warning'>{crash}</font>  ANR:  <font color='warning'>{anr}</font>
".format(
                badjs=str(device_data[key]['badjs']), url=str(device_data[key]['url']),
                crash=str(device_data[key]['crash']), anr=str(device_data[key]['anr']))
  1. 使用 decode() 方法将字符串解码为 Unicode 字符串,例如:
string = '你好'.encode('utf-8').decode('utf-8')

这样就可以正确处理包含非 ASCII 字符的字符串了。

Python UnicodeDecodeError: 'ascii' codec can't decode byte 0xe7 in position 1: ordinal not in range(128) 解决方法

原文地址: https://www.cveoy.top/t/topic/qAMJ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录