import socket
target_host = 'www.baidu.com'
target_port = 80
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((target_host, target_port))
msg = 'get / http/1.1\r\nHost:baidu.com\r\n\r\n'
client.send(msg.encode('utf-8'))
response = client.recv(4096)
print(response)
client.close
為什么輸出的內容里 b'HTTP/1.1 400 Bad Request\r\n\r\n' 會有 b' ?
寫的udp 也是會有這兩個字符。
uj5u.com熱心網友回復:
b'....' 在python2 時引入,那時叫 binary string, Python 3 以后就叫位元組串 byte string 。 類似于C中的 char[ ], Java中的 bytes[ ]. 一個位元組一個字符,用ASCII 編碼。服務器回復的一般都是byte string, 兼容好啊
注意,python 里預設是 unicode. 當然你可以指定編碼
所以 一般地,判斷: ‘A’== b'A' 結果是 False
Python 還有些著名的串,比如正則中經常用的 r'...' raw string, Python 3.6以后引入的 f'... ' 格式串 format string
要轉換,得用decode()函式. str()不行
>>> s = b'hello, world'
>>> s
b'hello, world'
>>> str(s)
"b'hello, world'"
>>> s.decode('ascii')
'hello, world'
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/175167.html
上一篇:WireShark抓包后資料分析
