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

我的梦境 提交于 2019-12-01 15:57:27

问题


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

回答1:


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.




回答2:


You can use in operator with list.

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

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

>>> '3'.lower()
'3'



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



回答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()




回答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" or Class=="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




回答6:


Make the string lower case.:

Class.lower() == "three"


来源:https://stackoverflow.com/questions/30277347/if-else-statements-accepting-strings-in-both-capital-and-lower-case-letters-in-p

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!