在服务器端对字符串进行编码时出错。它抛出以下错误:
broadcast(bytes(msg,“ utf8”))TypeError:没有字符串的编码 论点
这是我的代码
HttpServletResponse
尽管我使用字符串参数对其进行编码。 我有什么想念的吗?
答案 0 :(得分:0)
如果name
是一个字符串,而您写了msg = "%s from has joined the chat!",name
,则将收到一个字符串元组,第一个元素是“%s from from join the chat!”,第二个是名称字符串的值。
对于连接字符串,请尝试:
msg = "%s from has joined the chat!" + name
或者在这种情况下可能是:
msg = name + "has joined the chat!"
答案 1 :(得分:0)
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()
确实可以不这样做
答案 2 :(得分:0)
你可以替换这个
msg = "%s from has joined the chat!",name
有了这个
msg = "%s from has joined the chat!" % name
还有这个
broadcast(bytes(msg, "utf8"))
有了这个
broadcast(msg.encode("utf8"))
就这些