Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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+")
like image 776
Sofia Avatar asked May 16 '15 15:05

Sofia


People also ask

How do you check if a string contains both upper and lowercase Python?

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.

How do you check if a letter is uppercase or lowercase in Python?

To check if a character is upper-case, we can simply use isupper() function call on the said character.


3 Answers

You can use in operator with list.

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

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

>>> '3'.lower()
'3'
like image 100
Tanveer Alam Avatar answered Oct 14 '22 03:10

Tanveer Alam


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.

like image 34
michaelpri Avatar answered Oct 14 '22 01:10

michaelpri


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+")
like image 4
Liam Marshall Avatar answered Oct 14 '22 03:10

Liam Marshall