If / else accepting strings in both uppercase and lowercase letters in python

Is there a quick way for the if if statement to accept a string regardless of whether it is lowercase, uppercase, or both in python?

I’m trying to write a piece of code into which you can enter the number “3”, as well as the word “three” or “three” or any other mixture of capital and lower case, and this will still be accepted by the expression “if” in the code. I know that I can use "or" to force it to accept "3", as well as any other string, but I do not know how to make it accept a string in several cases. So far I:

if (Class == "3" or Class=="three"): f=open("class3.txt", "a+") 
+7
python capitalize if-statement uppercase lowercase
source share
6 answers

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() .

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

The last thing you can check is "3" and "three" at the same time with in .

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

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

str.lower() final note - 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 cannot use in if 3 as an integer is possible Class value.

+8
source share

You can use the in operator with list .

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

For reference only, '3'.lower() returns string 3 .

 >>> '3'.lower() '3' 
+11
source share

You can simply cast all strings to lowercase and check only lowercase:

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

If you use string.lower() , you can turn the entire string into lowercase so you can check it in an if statement. Just replace the string with your actual string. So Class.lower()

+2
source share

Typically, to make an insensitive comparison, I will make my variable lowercase. Although Class is a risky name because Class is the s keyword, you can do the following

 Class = Class.lower() if(Class =="3" or Class=="three"): 

And so on

I would keep it as low as possible only if you do not need to save this case for anything later, and especially if you have other comparisons, for example, with the “four”, and

+2
source share

Make a string lowercase case .:

 Class.lower() == "three" 
+1
source share

All Articles