Earlier today I needed to iterate over a string 2 characters at a time for parsing a string formatted like "+c-R+D-E"
(there are a few extra letters).
I ended up with this, which works, but it looks ugly. I ended up commenting what it was doing because it felt non-obvious. It almost seems pythonic, but not quite.
# Might not be exact, but you get the idea, use the step
# parameter of range() and slicing to grab 2 chars at a time
s = "+c-R+D-e"
for op, code in (s[i:i+2] for i in range(0, len(s), 2)):
print op, code
Are there some better/cleaner ways to do this?
Consider
pip
installingmore_itertools
, which already ships with achunked
implementation along with other helpful tools:Output:
Maybe not the most efficient, but if you like regexes...
Great opportunity for a generator. For larger lists, this will be much more efficient than zipping every other elemnent. Note that this version also handles strings with dangling
op
sedit: minor rewrite to avoid ValueError exceptions.
izip_longest
requires Python 2.6( or higher). If on Python 2.4 or 2.5, use the definition forizip_longest
from the document or change the grouper function to:Dunno about cleaner, but there's another alternative:
A no-copy version: