Pythonic way to determine if one char of many in a string
clp2 at rebertia.com
Mon Feb 16 00:56:00 EST 2009
On Sun, Feb 15, 2009 at 9:17 PM, <python at bdurham.com> wrote:
> 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 ... :
> # flexible, but no short circuit on first match
> if [ char for char in word if char in 'aeiouAEIOU' ]:
Just use the fairly new builtin function any() to make it short-circuit:
if any(char.lower() in 'aeiou' for char in word):
Follow the path of the Iguana...
More information about the Python-list