Python 3 TypeError: Can’t convert ‘bytes’ object to str implicitly

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

  1. Python 3 Built-in Types
  2. Python Whois client example

One comment on “Python 3 TypeError: Can’t convert ‘bytes’ object to str implicitly

  1. Yo tengo un código similar, he tratado de hacerle alguna modificaciones pero no logro solucionar el problema.
    Estoy tratando de leer los valores de 3 sensores Arduino, HC-SR04, LM35 y DHT11, el DHT11 me da 3 valores (humedad, °C y °F), los 5 valores que trato de leer con el script Python son “int” en Arduino pero enviados como String.

    Script Python:

    import bluetooth

    moduloHC05 = “00:21:13:02:B5:20”
    puerto = 1
    conexion = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
    conexion.connect((moduloHC05, puerto))

    datos = “”
    while 1:
    try:
    datos += conexion.recv(4096)
    datos_end = datos.find(‘\n’)
    if datos_end != -1:
    rec = datos[:datos_end]
    print(datos)
    #datos = datos[datos_end + 1:]
    except KeyboardInterrupt:
    break

    conexion.close()

    Error:
    Traceback (most recent call last):
    File “/home/pi/Desktop/lecturaHC05.py”, line 11, in
    datos += conexion.recv(4096)
    TypeError: Can’t convert ‘bytes’ object to str implicitly

    Reply

Leave a Comment

Your email address will not be published. Required fields are marked *