【发布时间】:2020-04-10 12:37:57
【问题描述】:
我正在解析当前为字节形式的 html,方法是将其转换为字符串,然后将其写入列表。 我想删除所有正斜杠(甚至只是很好地处理转义字符)。
这是我的代码:
picture_divs = [b'<img alt="Python\'s Confusing me." class="" src="https://link_goes_here" style="whatever;"/>']
def get_alt_text(picture_divs):
alt_text = []
for i, elem in enumerate(picture_divs):
str_elem = str(elem).replace('\\', '') # Convert bytes -> strings
start_index = int(str_elem.find('alt='))
end_index = int(str_elem.find('class='))
alt_text.append(str_elem[start_index + 4:end_index])
return alt_text
alt_text_return = get_alt_text(picture_divs)
print(alt_text_return)
输出: ['"Python 让我很困惑。" ']
期望的输出: ['“Python 让我很困惑。” ']
【问题讨论】:
-
您想要的输出是不可能的。字符串由
'分隔,因此这些 必须 被转义,否则它们会关闭字符串。这是一个语法错误:'"Python's Confusing me." '