Python 3 TypeError: Cant convert bytes object to str implicitly
By:Roy.LiuLast updated:2019-08-17
Converting a Python 2 socket example to Python 3
whois.py
import sys import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(("whois.arin.net", 43)) s.send((sys.argv[1] + "\r\n").encode()) response = "" while True: data = s.recv(4096) response += data if not data: break s.close() print(response)
If compile with Python 3, it prompts the following error?
Traceback (most recent call last): File "C:\repos\hc\whois\python\whois.py", line 12, in <module> response += data TypeError: Can't convert 'bytes' object to str implicitly
Solution
In Python 3, the socket returns data as bytes (it was string in Python 2). Since the response is a string, you can’t add two different types (bytes + string) directly. To fix it, you need to convert the type :
#Solution 1 Convert the response from string to bytes
whois.py
import sys import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(("whois.arin.net", 43)) s.send((sys.argv[1] + "\r\n").encode()) #Convert response to bytes response = b"" # or use encode() #response = "".encode() while True: data = s.recv(4096) response += data if not data: break s.close() print(response.decode())
#Solution 2 Convert the data from bytes to string
whois.py
import sys import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(("whois.arin.net", 43)) s.send((sys.argv[1] + "\r\n").encode()) response = "" while True: data = s.recv(4096) #convert data from bytes to string #response += data response += data.decode() if not data: break s.close() print(response)
References
From:一号门
COMMENTS