我正在使用帶有 Web 客戶端的 GET 請求決議資訊。我有一個基于該資料的連接字串,我想根據以下模式拆分字串:“\r\n”。我基本上希望每一位標題資訊都在自己的行上。另外我想排除身體資訊。
這是我想拆分的示例字串的一部分:
'HTTP/1.1 400 Bad Request\\r\\nDate: Tue, 26 Oct 2021 11:26:46 GMT\\r\\nServer:
我有一個用于決議資訊的函式,我嘗試使用正則運算式和拆分,但我不斷收到錯誤訊息(我是 Python 和網路的新手)。以下是我嘗試過的一些示例(網路資訊是要拆分的字串):
header = webinformation.splitlines()
for x in range(len(header)):
print(header[x])
這是我嘗試過的正則運算式的一個示例
print(re.split('\\r\\n', webinformation))
我怎樣才能在自己的行上列印每一位資訊?我不確定這是否是轉義字符的問題?
uj5u.com熱心網友回復:
您有\r\n四個字符的行分隔符。
您不需要正則運算式,因為它是固定文本。使用str.split:
text = 'HTTP/1.1 400 Bad Request\\r\\nDate: Tue, 26 Oct 2021 11:26:46 GMT\\r\\nServer:'
for line in text.split(r'\r\n'):
print(line)
請參閱Python 演示。
輸出:
HTTP/1.1 400 Bad Request
Date: Tue, 26 Oct 2021 11:26:46 GMT
Server:
uj5u.com熱心網友回復:
像這樣:
? ~ ipython
Python 3.8.10 (default, Jun 2 2021, 10:49:15)
Type 'copyright', 'credits' or 'license' for more information
IPython 7.28.0 -- An enhanced Interactive Python. Type '?' for help.
In [1]: s = 'HTTP/1.1 400 Bad Request\\r\\nDate: Tue, 26 Oct 2021 11:26:46 GMT\\r\\nServer:'
In [2]: s.replace('\\r\\n', '\n').splitlines()
Out[2]: ['HTTP/1.1 400 Bad Request', 'Date: Tue, 26 Oct 2021 11:26:46 GMT', 'Server:']
uj5u.com熱心網友回復:
您可以在不使用正則運算式的情況下用 \n 替換空格:
a = 'HTTP/1.1 400 Bad Request\\r\\nDate: Tue, 26 Oct 2021 11:26:46 GMT\\r\\nServer:'
print(a.replace('\\r\\n', '\n'))
輸出:
HTTP/1.1 400 Bad Request
Date: Tue, 26 Oct 2021 11:26:46 GMT
Server:
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/337889.html
下一篇:Java版人臉檢測詳解下篇:編碼
