[Python-ideas] str.find() and friends support a lists of inputs

Steven D'Aprano steve at pearwood.info
Fri Apr 18 03:49:32 CEST 2014


On Thu, Apr 17, 2014 at 01:14:23PM -0700, Andrew Barnert wrote:
> On Apr 17, 2014, at 11:52, Alex Rodrigues <lemiant at hotmail.com> wrote:
> 
> > It's a fairly common problem to want to .find() or .replace() or 
> > .split() any one of multiple characters.
> 
> I like your solution, except for one thing. Explicitly requiring a 
> list of arguments rather than, say, a tuple or an iterator, seems 
> unnecessarily restrictive. However, allowing any iterable of strings 
> doesn't work because a string is itself an iterable of strings.
> 
> There are a few cases where Python deals with this problem by treating 
> tuples specially (e.g., % formatting), but I don't think anyone wants 
> to extend that solution.

I do! That makes the decision really simple: if the argument is a tuple, 
it is treated as multiple values, otherwise it is treated as a single 
value. That's how other string methods operate:

py> 'abcd'.startswith(('xyz', 'abc'))
True
py> 'abcd'.startswith(['xyz', 'abc'])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: startswith first arg must be str or a tuple of str, not list

so it's quite easy to learn, with no concerns about whether or not the 
argument will accept a set or a dict or iterators...



-- 
Steven


More information about the Python-ideas mailing list