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+")
Python String islower() The islower() method returns True if all alphabets in a string are lowercase alphabets. If the string contains at least one uppercase alphabet, it returns False.
To check if a character is upper-case, we can simply use isupper() function call on the said character.
You can use in
operator with list
.
if Class.lower() in ['3', 'three']:
Just for reference '3'.lower()
returns string 3
.
>>> '3'.lower()
'3'
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
.
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+")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With