[英]How do I change my data from bytes to strings in this function?
I have some code for networking program. 我有一些用于联网程序的代码。 and its
及其
def dataReceived(self, data)
print(f"Received quote: {data}")
self.transport.loseConnection()
This function is printing 此功能正在打印
Received quote: b'\x00&C:\\Users\\.pycharm2016.3\\config\x00&C:\\users\\pycharm\\system\x00\x03--'
How would i change my code to fix this? 我将如何更改代码以解决此问题?
I think I know that what is happening is what is being printed out is the code in bytes and it needs to be converted to a string, but do I do this on the server or client side of the program? 我想我知道正在打印的是字节代码,需要将其转换为字符串,但是我要在程序的服务器或客户端执行此操作吗?
When i write 当我写
print(f"receivedquote: {data}".decode('utf-8')
that does not do the trick. 不能解决问题。 I get a lot of errors.
我收到很多错误。 How can I ask this question better to find a solution?
我如何更好地问这个问题以找到解决方案?
Decode the actual data: 解码实际数据:
data = data.decode('utf-8')
At this point, data
is a Python Unicode string which you can print, search, slice, etc. 此时,
data
是Python Unicode字符串,您可以打印,搜索,切片等。
(Your data doesn't particularly look like UTF-8 but I'm not going to second-guess that; it's not clearly not UTF-8, either.) (您的数据看上去并不特别像UTF-8,但我不会对此进行猜测;显然也不是不是UTF-8。)
It's generally a good idea to convert to Unicode immediately after receiving a byte string, and have the rest of your program operate on strings. 通常,在接收到字节字符串后立即转换为Unicode,并让程序的其余部分对字符串进行操作是一个好主意。 If you need to encode back to bytes, similarly do that only at the perimeter, jut before the data leaves your program.
如果您需要编码回字节,则类似地,仅在数据离开程序之前伸出周边。 ( Ned Batchelder calls this "Unicode sandwiching.")
( Ned Batchelder将此称为“ Unicode三明治”。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.