[英]Python 3.8 TypeError: can't concat str to bytes - TypeError: a bytes-like object is required, not 'str'
Very new to coding.对编码非常陌生。 This was the initial code I was trying to get to run but have found it is incompatible with python 3 because of how it handles strings and bytes.
这是我试图运行的初始代码,但发现它与 python 3 不兼容,因为它处理字符串和字节的方式。
def opensocket():
s = socket.socket()
s.connect((HOST,PORT))
s.send("PASS " + PASS + "\r\n")
s.send("NICK " + IDENT + "\r\n")
s.send("JOIN #" + CHANNEL + "\r\n")
return s
I think I need to encode these strings into bytes but all the conversion methods I've tried have given errors.我想我需要将这些字符串编码为字节,但我尝试过的所有转换方法都给出了错误。 here are some i've tried.
这是我尝试过的一些。
def opensocket():
s = socket.socket()
s.connect((HOST,PORT))
s.send(b"PASS " + PASS + "\r\n")
s.send(b"NICK " + IDENT + "\r\n")
s.send(b"JOIN #" + CHANNEL + "\r\n")
and和
def opensocket():
s = socket.socket()
s.connect((HOST,PORT))
s.send("PASS " + PASS + "\r\n".encode())
s.send("NICK " + IDENT + "\r\n".encode())
s.send("JOIN #" + CHANNEL + "\r\n".encode())
return s
both of these give errors saying the str can't be concatenated into bytes any help?这两个都给出错误说 str 不能连接成字节有什么帮助吗?
edit: went through the suggested post but I'm gaining nothing from that.编辑:浏览了建议的帖子,但我没有从中获得任何好处。 it looks so different and I'm so new to this that I can't even tell where the string was he was trying to convert
它看起来如此不同,我对此很陌生,以至于我什至不知道他试图转换的字符串在哪里
In the case that PASS
, IDENT
and CHANNEL
are bytes
:在
PASS
, IDENT
和CHANNEL
是bytes
的情况下:
def opensocket():
s = socket.socket()
s.connect((HOST,PORT))
s.send(b"PASS " + PASS + b"\r\n")
s.send(b"NICK " + IDENT + b"\r\n")
s.send(b"JOIN #" + CHANNEL + b"\r\n")
In the case that PASS
, IDENT
and CHANNEL
are str
:在
PASS
、 IDENT
和CHANNEL
是str
的情况下:
def opensocket():
s = socket.socket()
s.connect((HOST,PORT))
s.send(b"PASS " + PASS.encode('ascii') + b"\r\n")
s.send(b"NICK " + IDENT.encode('ascii') + b"\r\n")
s.send(b"JOIN #" + CHANNEL.encode('ascii') + b"\r\n")
It's important to know what protocol you're using, to know what encoding actually to use.了解您使用的协议以及实际使用的编码非常重要。
'ascii'
is a safe bet, but it means you're limited in to ASCII-only characters, so if the protocol actually specifies UTF-8 strings, you should do .encode('utf-8')
instead. 'ascii'
是一个安全的选择,但这意味着你只能使用 ASCII 字符,所以如果协议实际上指定了 UTF-8 字符串,你应该.encode('utf-8')
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.