0

I have string like this that has a stringified byte substring inside of it as follows:

some_string = "b'Hurricane Mitch\\n'"

What is the best way to extract the nested b' string so that I can decode it properly in utf8?

2
  • How did you end up with this data? I would rather fix that. Commented Nov 23, 2020 at 15:18
  • I didn't generate it, it was provided to me and the original doesn't exist anymore so unfortunately it's not an option. Commented Nov 23, 2020 at 15:19

1 Answer 1

3

The most straightforward approach (that's still more powerful than you need, but probably not a security risk) is ast.literal_eval.

from ast import literal_eval
some_string = "b'Hurricane Mitch\\n'"
literal_eval(some_string).decode('utf-8') # 'Hurricane Mitch\n'
Sign up to request clarification or add additional context in comments.

Comments

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.