1
votes

I got a string of bytes string like below:

string1 = "b'\xe6\x88\x91\xe4\xbb\xac \xe7\xb4\xa2\xe8\xa6\x81 \xe6\x8e\xa8\xe5\xb9\xbf \xe7\x9a\x84 \xe6\x98\xaf\xe4\xb8\x80 \xe5\xbe\x97 \xe6\x96\xb9\xe6\x96\xb9 \xe6\x96\xb9\xe8\xa8\x80 \xe4\xb8\xba\xe5\x9f\xba \xe7\xa1\x80 \xe6\x96\xb9\xe8\xa8\x80 \xe4\xb8\x80 \xe5\x8c\x97\xe4\xba\xac \xe5\xb7\xb2 \xe5\x9b\xa0 \xe4\xb8\xba \xe6\xa0\x87\xe5\x87\x86 \xe7\x9a\x84 \xe6\x99\xae\xe9\x80\x9a \xe8\xaf\x9d \xe4\xbb\x96 \xe4\xbb\x8e \xe5\x84\xbf\xe7\xab\xa5 \xe6\x97\xb6\xe4\xbb\xa3 \xe8\xb5\xb7 \xe5\xb0\xb1 \xe5\x96\x9c\xe6\xac\xa2 \xe4\xb8\x8b \xe5\x9b\xb4\xe6\xa3\x8b \xe5\x9c\xa8 \xe5\x8d\x81\xe4\xba\x94 \xe5\xb2\x81 \xe7\x9a\x84 \xe6\x97\xb6\xe5\x80\x99 \xe5\xb0\xb1 \xe6\x98\xaf\xe6\x9c\x89 \xe5\x90\x8d \xe5\x85\xb6 \xe5\xb0\x91 \xe4\xba\x86'"

I want to convert string of bytes string into string so that i could use decode function to normal result.

1
Can you not just do new_string = st[2:-1] ? - RMRiver
This should work too str(string1) if there is a problem you are facing trying to implement mine or RMRiver's solutions, please edit your question to explain that. - Thunder Coder

1 Answers

2
votes

First, put an r before it so that the \x keeps both characters. Then ast.literal_eval() will work.

import ast

string1 = r"b'\xe6\x88\x91\xe4\xbb\xac \xe7\xb4\xa2\xe8\xa6\x81 \xe6\x8e\xa8\xe5\xb9\xbf \xe7\x9a\x84 \xe6\x98\xaf\xe4\xb8\x80 \xe5\xbe\x97 \xe6\x96\xb9\xe6\x96\xb9 \xe6\x96\xb9\xe8\xa8\x80 \xe4\xb8\xba\xe5\x9f\xba \xe7\xa1\x80 \xe6\x96\xb9\xe8\xa8\x80 \xe4\xb8\x80 \xe5\x8c\x97\xe4\xba\xac \xe5\xb7\xb2 \xe5\x9b\xa0 \xe4\xb8\xba \xe6\xa0\x87\xe5\x87\x86 \xe7\x9a\x84 \xe6\x99\xae\xe9\x80\x9a \xe8\xaf\x9d \xe4\xbb\x96 \xe4\xbb\x8e \xe5\x84\xbf\xe7\xab\xa5 \xe6\x97\xb6\xe4\xbb\xa3 \xe8\xb5\xb7 \xe5\xb0\xb1 \xe5\x96\x9c\xe6\xac\xa2 \xe4\xb8\x8b \xe5\x9b\xb4\xe6\xa3\x8b \xe5\x9c\xa8 \xe5\x8d\x81\xe4\xba\x94 \xe5\xb2\x81 \xe7\x9a\x84 \xe6\x97\xb6\xe5\x80\x99 \xe5\xb0\xb1 \xe6\x98\xaf\xe6\x9c\x89 \xe5\x90\x8d \xe5\x85\xb6 \xe5\xb0\x91 \xe4\xba\x86'"
bytes1 = ast.literal_eval(string1)
print(bytes1.decode('utf8'))  # 我们 索要 ...