Python 3 TypeError: Cant convert bytes object to str implicitly

摘要: Converting a Python 2 socket example to Python 3

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

上一篇: Spring MVC Form Check if a field has an error
下一篇: Spring embedded database examples
 评论 ( What Do You Think )
名称
邮箱
网址
评论
验证
   
 

 


  • 微信公众号

  • 我的微信

站点声明:

1、一号门博客CMS,由Python, MySQL, Nginx, Wsgi 强力驱动

2、部分文章来源于互联网, 若有侵权, 联系邮箱:summer@yihaomen.com, 同时欢迎大家注册用户,主动发布文章.

3、鄂ICP备14001754号-3, 鄂公网安备 42280202422812号