2016-11-11 106 views
1

我有一个这样的字符串:将字符串转换为字节对象?

text = 'b\'"Bill of the one\\xe2\\x80\\x99s store wanted to go outside.\'' 

这显然意味着是字节格式,但是当我看对象的类型,它返回:

type(text) 
<class 'str'> 

我试图编码的字节然后解码,但这是结果:

text.encode("utf-8").decode("utf-8") 
'b\'"Bill of the oneâ\x80\x99s store wanted to go outside.\'' 

如何才能正确格式化文本?

回答

2

至于另一个可能的方法,在我看来,你有字符串是一个字节对象上调用repr的结果。你可以通过调用ast.literal_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.' 
0

为什么你要对字符串对象进行编码和解码,如果你这样做,你将会以任何方式来到相同的状态(即)字符串,只是编码就足够了。现在

text = 'b\'"Bill of the one\\xe2\\x80\\x99s store wanted to go outside.\'' 
type(text) #This will output <class 'str'> 

,为字节的对象只是利用下面摘录

byte_object=text.encode("utf-8") 
type(byte_object) #This will output <class 'bytes'> 
+0

权,但现在'byte_object == B'B \'“的一个\\ \\ XE2法案'''' – brianpck

+0

好吧,我不清楚看到@brianpck的问题我可以理解你的要求,你可以使用ast来表示这个意思。 –