如何在Python中打印带有双反斜杠特殊字符的字符串(如\\xe7)

我有一个字符串(从 HTML 网页请求获得),其中包含特殊字符:


'Dimarts, 10 Mar\\xe7 2020'

如果我打印此字符串,它会正确转义双反斜杠并仅打印一个:


Dimarts, 10 Mar\xe7 2020

但我想要的是打印真实的字符,即字符 92 = ç


Dimarts, 10 Març 2020

我尝试过用一个反斜杠替换双反斜杠,甚至使用 html 库取消转义,但没有成功。如果我用文本手动设置一个新变量,然后打印它,它会起作用:


print('Original: ', repr(text))

print('Direct  : ', text)

print('Option 1: ', text.replace('\\\\', '\\'))

print('Option 2: ', text.replace(r'\\', '\\'))

print('Option 3: ', text.replace(r'\\', chr(92)))

print('Option 4: ', text.replace('\\', chr(92)))

print('Option 5: ', html.unescape(text))

text = 'Dimarts, 10 Mar\xe7 2020'

print('Manual:   ', text)

结果却从来没有像预期的那样:


Original:  'Dimarts, 10 Mar\\xe7 2020'

Direct  :  Dimarts, 10 Mar\xe7 2020

Option 1:  Dimarts, 10 Mar\xe7 2020

Option 2:  Dimarts, 10 Mar\xe7 2020

Option 3:  Dimarts, 10 Mar\xe7 2020

Option 4:  Dimarts, 10 Mar\xe7 2020

Option 5:  Dimarts, 10 Mar\xe7 2020

Manual:    Dimarts, 10 Març 2020

有没有办法让Python正确处理特殊字符?


白衣非少年
浏览 58回答 2
2回答

慕妹3242003

好吧,事实证明我在 Windows 中对文件进行编码时遇到了问题。我必须在处理之前对其进行解码。因此,这样做解决了问题:htmlfile = urllib.request.urlopen('http://www.somewebpage.com/')for line in htmlfile:    line = line.decode('cp1252')也可以解码整个 html:htmlfile = urllib.request.urlopen('http://www.somewebpage.com/').read()htmldecoded = htmlfile.decode('cp1252')这样做解决了问题,我可以正确打印字符串。

白猪掌柜的

不确定这是否是您想要的,但是:print(chr(231))将打印您想要的字符。它还将由以下人员打印:print(u"\xe7")
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5