How do I convert an iterator over bytes into a str?
pavlovevidence at gmail.com
Wed Aug 19 05:02:34 CEST 2009
On Aug 18, 3:24 pm, markscottwright <markscottwri... at gmail.com> wrote:
> This does what I expected:
> In : list(iter([1,2,3,4,5]))
> Out: [1, 2, 3, 4, 5]
> But this appears to be doing a __repr__ rather than making me a nice
> In : str(iter("four score and seven years ago"))
> Out: '<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 : "".join(iter("four score and seven years ago"))
> Out: 'four score and seven years ago'
This is the correct way.
If the syntax bothers you can always do this:
I think "".join is ugly as hell but in this case convenience beats
beauty for me.
More information about the Python-list