Python 是否将包含字节字符的字符串对象转换为字节对象?

Python 是否将包含字节字符的字符串对象转换为字节对象?,python,unicode,Python,Unicode,我有这样一个字符串: text = 'b\'"Bill of the one\\xe2\\x80\\x99s store wanted to go outside.\'' 这显然是字节格式的,但是当我查看对象的类型时,它返回: type(text) <class 'str'> 如何正确格式化文本?为什么要对字符串对象进行编码和解码?如果这样做,您将进入相同的状态(即)字符串,只需编码就足够了 text = 'b\'"Bill of the one\\xe2\\x80\\x

我有这样一个字符串:

text = 'b\'"Bill of the  one\\xe2\\x80\\x99s store wanted to go outside.\''
这显然是字节格式的,但是当我查看对象的类型时,它返回:

type(text)  
<class 'str'>

如何正确格式化文本?

为什么要对字符串对象进行编码和解码?如果这样做,您将进入相同的状态(即)字符串,只需编码就足够了

text = 'b\'"Bill of the  one\\xe2\\x80\\x99s store wanted to go outside.\''
type(text) #This will output <class 'str'>
text='b\'“一张账单\\xe2\\x80\\x99s商店想出去。”
键入(文本)#这将输出
现在,对于byte对象,只需使用下面的代码段

byte_object=text.encode("utf-8")
type(byte_object) #This will output <class 'bytes'>
byte\u object=text.encode(“utf-8”)
类型(byte_object)#这将输出

为什么要对字符串对象同时进行编码和解码?如果这样做,无论如何都会进入相同的状态(即)字符串,只需编码就足够了

text = 'b\'"Bill of the  one\\xe2\\x80\\x99s store wanted to go outside.\''
type(text) #This will output <class 'str'>
text='b\'“一张账单\\xe2\\x80\\x99s商店想出去。”
键入(文本)#这将输出
现在,对于byte对象,只需使用下面的代码段

byte_object=text.encode("utf-8")
type(byte_object) #This will output <class 'bytes'>
byte\u object=text.encode(“utf-8”)
类型(byte_object)#这将输出

作为另一种可能的方法,在我看来,您拥有的字符串是对字节对象调用
repr
的结果。通过调用
ast.literal\u eval
,可以反转
repr

>>> import ast
>>> x = b'test string'
>>> y = repr(x)
>>> y
"b'test string'"
>>> ast.literal_eval(y)
b'test string'
或者在您的情况下:

>>> x = 'b\'"Bill of the  one\\xe2\\x80\\x99s store wanted to go outside.\''
>>> import ast
>>> ast.literal_eval(x)
b'"Bill of the  one\xe2\x80\x99s store wanted to go outside.'

另一种可能的方法是,在我看来,您拥有的字符串是对字节对象调用
repr
的结果。通过调用
ast.literal\u eval
,可以反转
repr

>>> import ast
>>> x = b'test string'
>>> y = repr(x)
>>> y
"b'test string'"
>>> ast.literal_eval(y)
b'test string'
或者在您的情况下:

>>> x = 'b\'"Bill of the  one\\xe2\\x80\\x99s store wanted to go outside.\''
>>> import ast
>>> ast.literal_eval(x)
b'"Bill of the  one\xe2\x80\x99s store wanted to go outside.'

是的,但是现在一家店的账单想出去。\''byte\u object==b'b\''s商店想出去。\''ok,我不清楚看到@brianpck的问题,我可以理解你的要求,你可以使用ast,这是为了这个。是的,但是现在
byte\u object==b'b\'一张账单\\xe2\\x80\\x99s商店想出去。\''
好的,我不清楚看到@brianpck时的问题。我可以理解您的要求,您可以使用ast,这是专门用于此目的的。