无法在我的客户端中隐式地将字节转换为str

时间:2014-02-15 16:10:42

标签: python sockets

代码

host = "127.0.0.1"
port = 4446

from socket import *

s = socket(AF_INET, SOCK_STREAM)

s.connect((host,port))

msg = s.recv(1024)

print("Message From Server : " + msg)

s.close

我有错误作为标题,所以我想我不需要在这里任何更多请帮助我,我迷路了> _>我是插座的小伙子。

1 个答案:

答案 0 :(得分:1)

通过致电bytes.decode(),您可以从str获取bytes个对象:

>>> b = b'abitrary bytes'
>>> type(b)
<class 'bytes'>
>>> s = b.decode('utf-8')
>>> type(s)
<class 'str'>

>>> print(' from server ' + b)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't convert 'bytes' object to str implicitly
>>> print(' from server ' + s)
 from server abitrary bytes

print("Message From Server : " + msg.decode('utf-8')) 
#                                   ^^^^^^^^^^^^^^^^

您可以省略'utf-8',因为它是默认值。


BTW,最后一行缺少()

s.close()
#      ^^