【问题标题】:UnicodeEncodeError: 'decimal' codec can't encode character u'\x00' in position 8: invalid decimal Unicode stringUnicodeEncodeError:“十进制”编解码器无法在位置 8 编码字符 u'\x00':无效的十进制 Unicode 字符串
【发布时间】:2023-04-09 19:38:01
【问题描述】:

这条线给了我一个UnicodeEncodeError

studentID = int(studentID.unicode_markup.encode('utf-8').decode('utf-8', 'ignore'))

具体的错误是这个UnicodeEncodeError: 'decimal' codec can't encode character u'\x00' in position 8: invalid decimal Unicode string

如果我将这一行改为:

studentID = int(studentID.unicode_markup.encode('utf-8'))

我收到此错误:

ValueError: invalid literal for int() with base 10: '\xc2\xa0\xc2\xa0100\xc2\xa0\xc2\xa0'

我已尝试指定不同的编码(如“ascii”),但仍然出现相同的错误。

非常感谢您的帮助。

【问题讨论】:

  • 字符串已经是 unicode,为什么还要对它进行编码和解码?您需要做的就是直接传入字符串:即int(studentID.unicode_markup)。字符串的开头和结尾有不间断的空格,但int() 会自动去掉这些空格。
  • int(studentID.unicode_markup) 给我错误:UnicodeEncodeError: 'decimal' codec can't encode character u'\x00' in position 8: invalid decimal Unicode string
  • html 文档必须包含空字符。你从哪里得到这个文件?你在下载吗?如果是这样,您如何将其转换为 unicode?​​span>

标签: python python-2.7 unicode encoding utf-8


【解决方案1】:

100 前后的字符串中有一些不可见的字符。因此int 函数失败,因为它无法将此字符串转换为 int。

在尝试转换为 int 之前尝试以下方法来解析任何数字:

import re

# find all characters in the string that are numeric.
m = re.search(r'\d+', studentID.unicode_markup)
numeric = m.group() # retrieve numeric string
int(numeric) # returns 100

【讨论】:

  • 我现在得到这个错误:UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 0: ordinal not in range(128)
  • @VishwaIyer - 修改为适用于字符串包含数字的所有情况,并且您希望提取该数字以转换为 int。
  • 可能这是最可靠的方法。您不需要将字符串编码为 UTF-8,只需使用 m = re.search(r'\d+', studentID.unicode_markup)
  • @VishwaIyer 没问题。只是出于好奇,是否有任何理由将原始字符串编码为utf-8?您应该能够在原始 unicode_markup 上运行 re.search 并获得相同的结果。
  • @MartinKonecny 老实说我不知道​​。我是编码和解码的新手,这对我来说真的很困惑。在我花了几个小时试图解决我的问题之后,你的代码才起作用。我真的不想冒代码不再工作的风险。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-11-10
  • 2014-12-28
  • 2013-04-21
  • 2015-04-13
  • 2018-07-07
  • 2011-04-05
相关资源
最近更新 更多