Python 3 how to convert a list of bytes objects to a list of strings?
Chris Green
cl at isbd.net
Fri Aug 28 03:52:14 EDT 2020
Chris Angelico <rosuav at gmail.com> wrote:
> 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:
>
Yes, of course, it was just a 'quick and dirty' to make the point.
> But this is a really good job for a list comprehension:
>
> sss = [str(word) for word in bbb]
>
That seems the way to do it, thanks.
--
Chris Green
ยท
More information about the Python-list
mailing list