Martec Martec - 3 days ago 3
Python Question

Avoid repeating variable when comparing it to different characters (x == a or x == b or x==...)

Like in the following code; how do I avoid repeating "char =="?

for char in s:
if char == 'a' or char == 'e' or char == 'i' or char == 'o' or char == 'u':
do...


Is it possible to approximate the second line to what one would say in natural language: "if char is equal to a, e, i, o, or u..." ?

Answer

You can use the in-operator to check if a char exists in a string:

if char in "aeiou":
    #Do something
Comments