Search code examples
pythonif-statementuppercaselowercasecapitalize

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


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

Solution

  • Just convert Class to lowercase using str.lower() and test it.

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

    Of course, you can also use str.upper() too.

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

    One last thing is that you can check for "3" and "three" at the same time using in.

    if Class.lower() in {"3", "three"}:
        f=open("class3.txt", "a+")
    

    When using in for an if statement, you have several options. You can use a set, {"3", "three"}, which I used, a list, ["3", "three"], or a tuple, ("3", "three").

    One last thing to note is that calling str.lower() or str.upper() on "3" will give you "3", but calling it on the integer 3, will throw an error, so you can't use in if 3 as an integer is a possibly value for Class.