在服务器端对字符串进行编码时出错。它抛出以下错误:
广播(字节(msg, "utf8"(( 类型错误: 不带字符串的编码 论点
这是我的代码
msg = "%s from has joined the chat!",name
broadcast(bytes(msg, "utf8"))
虽然我用字符串参数对它进行编码。 我缺少什么吗?
如果name
是一个字符串并且你写msg = "%s from has joined the chat!",name
,您将收到一个字符串元组,第一个元素是"%s来自已加入聊天!",第二个元素是名称字符串的值。
要连接字符串,请尝试:
msg = "%s from has joined the chat!" + name
或者在这种情况下可能是:
msg = name + "has joined the chat!"
bytes()
不适用于使用 % 格式制作的字符串,您可以使用以下方法进行格式化:
msg = "{} from has joined the chat!".format(name)
或来自 Python 3.6
:msg = f"{name} from has joined the chat!"
这是因为在您的代码中msg
实际上是一个元组(尝试查看type(msg)
(,像print()
这样的函数可以将该元组转换为字符串,但bytes()
不会这样做
你可以替换这个
msg = "%s from has joined the chat!",name
有了这个
msg = "%s from has joined the chat!" % name
而这个
broadcast(bytes(msg, "utf8"))
有了这个
broadcast(msg.encode("utf8"))
就这样