[Python-ideas] An iterable version of find/index for strings?

Giampaolo RodolĂ  g.rodola at gmail.com
Fri Apr 5 12:11:45 CEST 2013


2013/4/5 Tom Schumm <phong at phong.org>:
> Should Python strings (and byte arrays, and other iterables for that matter)
> have an iterator form of find/rfind (or index/rindex)? I've found myself
> wanting one on occasion, and having more iterable things seems to be the
> direction the language is moving.
>
> Currently, looping over the instances of a substring in a larger string is a
> bit awkward. You have to keep track of where you are, and you either have have
> to watch for the -1 sentinel value or catch the ValueError. A "for idx in ..."
> construction would just be cleaner. You could use re.finditer, but a string
> method seems a more lightweight/efficient/obvious.
>
> The best name I can think of would be "finditer()" like re.finditer(). Using
> "ifind" (like izip) would be confusing, because it could be mistaken for case-
> insensitive find. I thought of "iterfind" like the old dict.iteritems, and
> ElementTree.iterfind but "iterrfind" (iterable rfind) is unattractive. I also
> think "find" is a more obvious verb than "index".
>
> I've got a simple Python implementation on gist:
> https://gist.github.com/fwiffo/5233377
>
> It includes an option to include overlapping instences, which may not be
> necessary (it's not present in e.g. re.finditer).

+1.

> I could imagine it as a method on str/unicode/bytes/list/tuple objects, or
> maybe as a function in itertools.

I would personally prefer the former.

--- Giampaolo
https://code.google.com/p/pyftpdlib/
https://code.google.com/p/psutil/
https://code.google.com/p/pysendfile/



More information about the Python-ideas mailing list