Python-如何检查单词是否包含大写和小写

时间:2018-08-17 03:07:38

标签: python

我正在做一个学校项目。 我对如何使(if)语句检测到大小写字符感到困惑。 我试图在if语句中使用“和”,但这太长了。 我当前的输入是:

a=input('Line: ')
if 'robot' in a:
 print('There is a small robot in the line.')
elif ('robot'.upper()) in a:
 print('There is a big robot in the line.')
elif b in a:
 print('There is a medium robot in the line.')
else:
 print('No robots here.')

别介意(b)我只是在弄清楚我不知道如何解释的事情。 我正在寻找的输出示例如下:

There is a "robot" in the line
then it would print
'There is a robot in the line'

程序将同时检查大小写字符。 如果输入有全部大写,它将打印出来 排队有一个大机器人 如果输入只有小写字母,那么它将只打印 生产线中有一个小型机器人。 如果输入的大小写都将输出: 生产线中有一个中型机器人。

4 个答案:

答案 0 :(得分:1)

在检查输入字符串中是否包含小写robot之前,可以先将输入小写:

更改:

elif b in a:

收件人:

elif 'robot' in a.lower():

答案 1 :(得分:0)

如何将reIGNORECASE一起使用来检查(b)情况。这意味着匹配单词“ robot”,“ Robot”,“ rObot” ...

import re

def check_robot(s):
    if re.search(r"robot", s):
        print("There is a small robot in the line.")
    elif re.search(r"ROBOT", s):
        print("There is a big robot in the line.")
    elif re.search(r"robot",s,re.IGNORECASE):
        print("There is a medium robot in the line.")
    else:
        print("'No robots here.'")

答案 2 :(得分:0)

您要使用not islower()和isupper()来获取混合字符串检查。这是有效的代码!

    a=input('Line: ')
    if 'robot' in a:
        print('There is a small robot in the line.')
    elif ('robot'.upper()) in a:
        print('There is a big robot in the line.')
    elif not a.islower() and not a.isupper():
        print('There is a medium robot in the line.')
    else:
        print('No robots here.')

答案 3 :(得分:0)

尝试一下:

words=["robot","ROBOT","ROBot","APPLE","Nuts"]
res=["UPPER" if w.isupper() else ("LOWER" if w.islower() else "MIXEDCASE") for w in words]  
print(res)

输出:

['LOWER', 'UPPER', 'MIXEDCASE', 'UPPER', 'MIXEDCASE']