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?

E. Ron
  • 51
  • 4
  • 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')` – furas Jun 12 '21 at 02:18
  • I think [this](https://stackoverflow.com/questions/606191/convert-bytes-to-a-string) is what your looking for. – thekid77777 Jun 12 '21 at 02:38

1 Answers1

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']
ThePyGuy
  • 17,779
  • 5
  • 18
  • 45