将输入()转换为 Python 3 中的字节?

Jho*_* Zu 3 python python-3.x

自从我开始使用 Python 的第 3 版以来,我在通过套接字发送字符串时遇到了很多问题。我知道要在套接字中发送字符串,'b'必须在字符串之前放置a才能将其转换为字节。但是当我必须将 an 转换input()为字节时会发生什么?它是如何完成的?

我需要将键盘写入的消息发送到套接字:

import socket

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(("localhost",7500))

msg = input()
client.send(msg) 
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试时,出现以下错误:

TypeError: a bytes-like object is required, not 'str'
Run Code Online (Sandbox Code Playgroud)

有人可以告诉我如何转换input()为字节吗?我总是使用 2.7 版本,我不明白为什么版本 3 对套接字的处理如此刺激。:(

Oli*_*çon 11

您需要encode像这样发送消息:

msg = input().encode()
Run Code Online (Sandbox Code Playgroud)

在 Python 2 中不需要这样做的原因是因为当时 unicode 字符串是它们自己的类型,但在 Python 3 中所有字符串现在默认都是 unicode