E. Ron
E. Ron

Reputation: 61

Python: How to decode (utf-8) bytearray object in string format back into string?

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?

Upvotes: 1

Views: 2708

Answers (1)

ThePyGuy
ThePyGuy

Reputation: 18426

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']

Upvotes: 1

Related Questions