【发布时间】:2019-03-12 01:17:10
【问题描述】:
python3 中的字符串有问题。我的 var g 是一个普通的字符串。但其中有一个烦人的“xe2x80x93”,因为它来自一个网络解析器。我想将其转换为合适的字符 "-"。
content = str(urllib.request.urlopen(site, timeout=10).read())
g = content.split('<h1 itemprop="name"')[1].split('</span></h1>')[0].split('<span>')[1].replace("\\", "")
print(type(g)) --> string
print(g) --> "Flash xe2x80x93 der rote Blitz"
print(g.encode('latin-1').decode('utf-8')) --> AttributeError: 'str' object has no attribute 'decode'
print(repr(g.decode('unicode-escape'))) --> AttributeError: 'str' object has no attribute 'decode'
print(g.encode('ascii','replace')) --> b'Flash xe2x80x93 der rote Blitz'
print(bytes(g, "utf-8").decode()) --> "Flash xe2x80x93 der rote Blitz"
print(bytes(g, "utf-8").decode("unicode_escape")) --> "Flash â der rote Blitz"
它是如何工作的?我没有更进一步。
【问题讨论】:
-
print(type(urllib.request.urlopen(site, timeout=10).read()))说什么? -
,所以我必须使用 ".decode("utf-8") ",而不是 str() ? -
谢谢!我已经更新了我的答案,给你一个应该适合你的替代第一行。
-
卢卡斯,是的——试试吧,让我/我们知道它是怎么回事:)
-
是的,它有效! @jedwards。非常感谢!
标签: python python-3.x string unicode-escapes