Add step to split

I would like an optional step parameter added to split, rsplit.
str.split(sep=None, maxsplit=-1, step=1)

If you had a string str=“one, two, three, four, five, six”, str.split(", ", step=2) would return a list:
[“one, two”, “three, four”, “five, six”]
The primary application I envision is formatting the output, eg, putting in a newline after every second comma.

You can take elements from the list 2 at a time and print them out.
Or even take elements from the list as long as the length is not exceeded.
And you can do this now without a chage to split().

2 Likes

I agree, this sounds rather too niche to be in the standardlib. If you have trouble coding this yourself, by all means ask.

I think something like

def f(string, pattern, step):
  return (pattern.join(x) for x in itertools.batched(string.split(pattern), step))

would do the trick.

2 Likes