If/else Statements Accepting Strings In Both Capital And Lower-case Letters In Python
Solution 1:
You can use in operator with list.
if Class.lower() in ['3', 'three']:
Just for reference '3'.lower() returns string 3.
>>> '3'.lower()
'3'Solution 2:
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.
Solution 3:
You can just force all strings to lower case and only check the lower case like this:
if (Class == "3"or Class.lower() == "three"):
f=open("class3.txt", "a+")
Solution 4:
If you use string.lower() you can turn the whole string to lower case so you can check it in an if statement. Just replace string with your actual string. So Class.lower()
Solution 5:
Typically to do an insensitive compare I'll make my variable lowercase. Though Class is a risky name to use because class is s keyword you could do the following
Class = Class.lower()
if(Class =="3"orClass=="three"):
And so forth
I'd save it as lower only if you don't need to preserve the case for anything later, and especially if you have other comparisons like against "four" as well
Post a Comment for "If/else Statements Accepting Strings In Both Capital And Lower-case Letters In Python"