2

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.

2
  • Can you not just do new_string = st[2:-1] ? Commented Jun 16, 2021 at 8:49
  • 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. Commented Jun 16, 2021 at 8:56

1 Answer 1

3

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'))  # 我们 索要 ...
Sign up to request clarification or add additional context in comments.

7 Comments

did you try your solution? because it doesn't seem to work.
@ThunderCoder I tried it and it does work
@BoarGules, look here:ide.geeksforgeeks.org/nLLLyLwNxZ to understand why I said that.
I copied your code, the this link: ide.geeksforgeeks.org/nLLLyLwNxZ, and it doesn't seem to work there
@ThunderCoder I looked there. You did not attempt to convert the bytes to a string, which is what OP wants. Try bytes1.decode() to see what I mean.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.