简体   繁体   English

如何在此函数中将数据从字节更改为字符串?

[英]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\\pych‌​arm\\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.

相关问题 如何将 seaborn 图表上的 integer 轴标签更改为我自己的字符串? - How do I change the integer axis labels on a seaborn chart to my own strings? 我怎么知道函数返回的是字符串还是字节? - How do I know if a function returns string or bytes? 如何在我的 MDDataTable 列表中删除我的字符串 - How do i strip my strings in my list for my MDDataTable 如何解码数据集中的字符串? (每个字符串由 '\x' 后跟数字格式化) - How do I decode strings in my data set? (Each string formatted by '\x' followed by numbers) 如何从函数内部更改变量的值? - How do i change the value of a variable but from inside a function? 如何连接来自 input() 的字符串? - How do I concatenate strings from input()? 如何将变量从一个函数传递到另一个函数? - How do I get my variables from one function to another? 如何从 pytest 引用我的 Azure 函数? - How do I reference my Azure function from pytest? 为什么我的 Python Scapy 数据包中有额外的数据。 只想发送最后 8 个字节 - Why do I have extra data in my Python Scapy Packet. only wanted to send the last 8 bytes 如何将数据从一个函数获取到另一个函数 - How do I get data from one function to another
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM