1

I have a list of data in form:

myList = ["bytearray(b'hi')", ...]

something like that.

I want to take each value in the list and convert into plain string form. So the given example should output :

hi

I know you do something like this:

data = bytearray(b'hi')
string = data.decode('UTF-8')

I am struggling with converting the initial string into a bytearray object to decode it back into the string. Any help?

2
  • 1
    how did you create this list ? It seems you converted all to strings. Maybe you should change code which creates this list - and stop converting to string. Now you may have to use eval("bytearray(b'hi')") to convert it back from string to bytesarray. eval("bytearray(b'hi')").decode('UTF-8') Commented Jun 12, 2021 at 2:18
  • I think this is what your looking for. Commented Jun 12, 2021 at 2:38

1 Answer 1

1

use eval to first convert the list items into bytearray object then call decode to convert bytearray object back to string.

[eval(each).decode('utf-8') for each in myList]

#output:
['hi']
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.