亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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

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

白衣非少年 2024-01-03 14:00:24
我有一個字符串(從 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 2020Option 1:  Dimarts, 10 Mar\xe7 2020Option 2:  Dimarts, 10 Mar\xe7 2020Option 3:  Dimarts, 10 Mar\xe7 2020Option 4:  Dimarts, 10 Mar\xe7 2020Option 5:  Dimarts, 10 Mar\xe7 2020Manual:    Dimarts, 10 Mar? 2020有沒有辦法讓Python正確處理特殊字符?
查看完整描述

2 回答

?
慕妹3242003

TA貢獻1824條經驗 獲得超6個贊

好吧,事實證明我在 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')

這樣做解決了問題,我可以正確打印字符串。


查看完整回答
反對 回復 2024-01-03
?
白豬掌柜的

TA貢獻1893條經驗 獲得超10個贊

不確定這是否是您想要的,但是:

print(chr(231))

將打印您想要的字符。

它還將由以下人員打印:

print(u"\xe7")


查看完整回答
反對 回復 2024-01-03
  • 2 回答
  • 0 關注
  • 205 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號