How do I convert an iterator over bytes into a str?

Carl Banks pavlovevidence at
Wed Aug 19 05:02:34 CEST 2009

On Aug 18, 3:24 pm, markscottwright <markscottwri... at> wrote:
> This does what I expected:
>     In [6]: list(iter([1,2,3,4,5]))
>     Out[6]: [1, 2, 3, 4, 5]
> But this appears to be doing a __repr__ rather than making me a nice
> string:
>    In [7]: str(iter("four score and seven years ago"))
>    Out[7]: '<iterator object at 0x0139F190>'

Unfortunately, str() is overloaded in that it tries to be both a sorta-
pretty-printer and a constructor.  You're trying to use it as a
constructor, but it wants to be a sorta-pretty-printer here.

Anyway, str is different from other container objects since, unlike
other containers, strings can't contain arbitrary Python objects.

> What's the correct way to turn an iterator over bytes into a string?
> This works, but, ewww:
>     In [8]: "".join(iter("four score and seven years ago"))
>     Out[8]: 'four score and seven years ago'

This is the correct way.

If the syntax bothers you can always do this:

    str.join("",iter("four score"))

I think "".join is ugly as hell but in this case convenience beats
beauty for me.

Carl Banks

More information about the Python-list mailing list