Martec Martec - 1 year ago 66
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':

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 Source

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

if char in "aeiou":
    #Do something
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download