Python 3 how to convert a list of bytes objects to a list of strings?

Chris Angelico rosuav at gmail.com
Thu Aug 27 16:41:25 EDT 2020


On Fri, Aug 28, 2020 at 6:36 AM Chris Green <cl at isbd.net> wrote:
>
> This sounds quite an easy thing to do but I can't find how to do it
> elegantly.
>
> I have a list of bytes class objects (i.e. a list containing sequences
> of bytes, which are basically text) and I want to convert it to a list
> of string objects.
>
> One of the difficulties of finding out how to do this is that 'list of
> bytes' tends to mean a bytes object with a sequence of bytes in it
> which is *not* what I'm after converting. :-)
>
> Obviously I can do:-
>
>     bbb = [b'aaa', b'bbb', b'ccc']
>     sss = []
>     for i in range(0, 2):
>         sss.append(str(bbb[i])
>
> but that does seem a bit clumsy.  Is there a better way?
>

Firstly, you shouldn't iterate over the range, but over the items themselves:

for word in bbb:

But this is a really good job for a list comprehension:

sss = [str(word) for word in bbb]

ChrisA


More information about the Python-list mailing list