if/else statements accepting strings in both capital and lower-case letters in python

Sofia picture Sofia · May 16, 2015 · Viewed 13.6k times · Source

Is there a quick way for an "if" statement to accept a string regardless of whether it's lower-case, upper-case or both in python?

I'm attempting to write a piece of code where the number "3" can be entered as well as the word "three"or "Three" or any other mixture of capital and lower-case and it will still be accepted by the "if" statement in the code. I know that I can use "or" to get it to accept "3" as well as any other string however don't know how to get it to accept the string in more than one case. So far I have:

if (Class == "3" or Class=="three"):
    f=open("class3.txt", "a+")

Answer

Tanveer Alam picture Tanveer Alam · May 16, 2015

You can use in operator with list.

if Class.lower() in ['3', 'three']:

Just for reference '3'.lower() returns string 3.

>>> '3'.lower()
'3'