我对python3中的字符串有问题。我的varg是一个普通字符串。但其中有一个恼人的“xe2x80x93”,因为它来自一个web解析器。我想把它转换成合适的字符“-”。你知道吗
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"
它是如何工作的?我再也没有了。你知道吗
你对
decode
的想法是正确的。你知道吗通过将输出包装在
str(...)
中的这一行:您可以将一个bytes对象转换为一个字符串(在
content
中,前面的b'
和后面的'
就是很明显的),或者,如果它已经被解码为ISO-8859-1,则什么也不做。你知道吗在这两种情况下,都不要删除包装
str
调用。你知道吗现在,内容将是
bytes
对象或str
对象。你知道吗因此,如果它是一个字符串,它将被解码(错误地)为ISO-8859-1。您需要将其编码回bytes对象,然后正确解码:
现在,您的
\xe2\x80\x93
字节应该正确地显示为:–更新:
从你的评论来看,你需要做的就是:
相关问题 更多 >
编程相关推荐