Standard lib version of something like enumerate() that takes a max count iteration parameter?
Peter Otten
__peter__ at web.de
Fri Jun 16 08:15:26 EDT 2017
Andre Müller wrote:
> # to impress your friends you can do
> for chunk in itertools.zip_longest(*[iter(s)]*4):
> chunked_str = ''.join(c for c in chunk if c) # generator expression
> inside join with condition
> print(chunked_str)
This can be simplified with a fillvalue
>>> s = "abracadabra"
>>> for chunk in itertools.zip_longest(*[iter(s)]*4, fillvalue=""):
... print("".join(chunk))
...
abra
cada
bra
but for sequences I prefer regular slicing:
>>> N = 4
>>> for start in range(0, len(s), N):
... print(s[start:start+N])
...
abra
cada
bra
More information about the Python-list
mailing list