Pythonic way to determine if one char of many in a string

J. Cliff Dyer jcd at sdf.lonestar.org
Mon Feb 16 19:34:17 CET 2009


On Mon, 2009-02-16 at 00:28 -0500, Nicolas Dandrimont wrote:
> * python at bdurham.com <python at bdurham.com> [2009-02-16 00:17:37 -0500]:
> 
> > I need to test strings to determine if one of a list of chars is
> > in the string. A simple example would be to test strings to
> > determine if they have a vowel (aeiouAEIOU) present.
> > I was hopeful that there was a built-in method that operated
> > similar to startswith where I could pass a tuple of chars to be
> > tested, but I could not find such a method.
> > Which of the following techniques is most Pythonic or are there
> > better ways to perform this type of match?
> > # long and hard coded but short circuits as soon as match found
> > if 'a' in word or 'e' in word or 'i' in word or 'u' in word or
> > ... :
> > -OR-
> > # flexible, but no short circuit on first match
> > if [ char for char in word if char in 'aeiouAEIOU' ]:
> > -OR-
> > # flexible, but no short circuit on first match
> > if set( word ).intersection( 'aeiouAEIOU' ):
> 
> I would go for something like:
> 
> for char in word:
>     if char in 'aeiouAEIUO':
>         char_found = True
>         break
> else:
>     char_found = False
> 
> (No, I did not forget to indent the else statement, see
> http://docs.python.org/reference/compound_stmts.html#for)
> 
> It is clear (imo), and it is seems to be the intended idiom for a search
> loop, that short-circuits as soon as a match is found.
> 

If performance becomes an issue, you can tune this very easily, so it
doesn't have to scan through the string 'aeiouAEIOU' every time, by
making a set out of that:

vowels = set('aeiouAEIOU')
for char in word 
    if char in vowels:
        return True
return False

Searching in a set runs in constant time.  


> Cheers,
> --
> http://mail.python.org/mailman/listinfo/python-list




More information about the Python-list mailing list