if / else语句接受python中的大写和小写字母的字符串 [英] if/else statements accepting strings in both capital and lower-case letters in python

查看:241
本文介绍了if / else语句接受python中的大写和小写字母的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种if语句可以快速接受字符串,无论它是小写,大写还是两者都在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?

我正在尝试编写一段代码,其中可以输入数字3以及三或三或任何其他混合资本和小写字母仍然可以被代码中的if语句接受。我知道我可以使用或来接受3以及任何其他字符串,但是不知道如何让它在多个案例中接受字符串。到目前为止,我有:

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


推荐答案

只需转换 Class 使用 str.lower()小写 并测试它。

Just convert Class to lowercase using str.lower() and test it.

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

当然,您也可以使用 str.upper()

Of course, you can also use str.upper() too.

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

最后一件事是你可以检查3 at同时在中使用

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

中使用时一个 if 语句,你有几个选择。你可以使用我用过的一套 {3,three} ,一个清单, [3,三 ] ,或元组,(3,3)

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

最后要注意的是调用 str。 lower() <$ 3上的c $ c> str.upper() 将为您提供3,但是在整数 3 上调用它会引发错误,所以你不能在 $ c>如果 3 ,整数是 Class

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.

这篇关于if / else语句接受python中的大写和小写字母的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆