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

Steven D'Aprano steve at pearwood.info
Tue Feb 17 07:09:50 EST 2009


Nicolas Dandrimont wrote:

> 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)

That might be better written as:

char_found = False
for char in word:
    if char in 'aeiouAEIUO':
        char_found = True
        break

or even:

char_found = False
for char in word:
    if char.lower() in 'aeiou':
        char_found = True
        break

but if word is potentially very large, it's probably better to reverse the
test: rather than compare every char of word to see if it is a vowel, just
search word for each vowel:

char_found = any( vowel in word for vowel in 'aeiouAEIOU' )

This moves the for-loop out of slow Python into fast C and should be much,
much faster for very large input.


-- 
Steven




More information about the Python-list mailing list