Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/354.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将转换后的字节转换回字符串_Python_Python 3.x_String_Type Conversion_Byte - Fatal编程技术网

Python 将转换后的字节转换回字符串

Python 将转换后的字节转换回字符串,python,python-3.x,string,type-conversion,byte,Python,Python 3.x,String,Type Conversion,Byte,我有一些文本是用文本文件写的,但不小心它们是用字节格式写的,例如:b'hello'。 当我试图通过python以文本文件的形式读取时,我得到的输出是“b'hello'”,但我需要“hello”。 我试图通过以下方式将其转换: "b'hello'".decode('utf-8') 但这会给出一个错误,因为str没有解码方法。任何有关这方面的帮助都将不胜感激 以下是文本文件外观的示例: 提到您的字节文本是实字节数据。因为如果你运行str(你的字节文本),值就会变成“b'hel

我有一些文本是用文本文件写的,但不小心它们是用字节格式写的,例如:b'hello'。 当我试图通过python以文本文件的形式读取时,我得到的输出是“b'hello'”,但我需要“hello”。 我试图通过以下方式将其转换:

"b'hello'".decode('utf-8')
但这会给出一个错误,因为str没有解码方法。任何有关这方面的帮助都将不胜感激

以下是文本文件外观的示例:

提到您的字节文本是实字节数据。因为如果你运行str(你的字节文本),值就会变成“b'hello”

从文件中检索字符串的方法之一

with open(file_path, 'r') as file:
    data = file.read()
    # the data is pure string like 'hello' already.
使用
b“hello”
这个
b
不应该在sting中,而是在字符串之前
如果要转换文件中的字符串,请执行[code>exec(f“variable=b”{old_variable}”)

如果已读取正确的字符串。。。只删除前面的
b'
并结束
,它会起作用吗?类似str[2:len(str)-1]“它们是以字节格式编写的”——最终写入文件的都是字节。问题在于读取它的方式,根据这一点,Python将把二进制数据转换为字符串,如果您允许它以文本模式打开文件,或者如果您以二进制模式打开文件,它将以字节序列的形式呈现给您。看起来是你做的。@ppanero它不仅仅是str和byte有b''的区别还有其他需要转换的字符现在有的是你的_byte_text=“b'hello'”而不是你的_byte_data=b'hello'@AyushTiwari我不知道。因此,我只是发布了从文本文件中获取文本字符串作为参考的方法。当我从文本文件中读取并将其存储在变量中时,它将以
variable=“b'hello'”格式存储
with open(file_path, 'r') as file:
    data = file.read()
    # the data is pure string like 'hello' already.