【问题标题】:Python- How to check if a word has lower and uppercasesPython-如何检查一个单词是否有小写和大写
【发布时间】:2018-08-17 03:07:38
【问题描述】:

我在做一个学校项目。 我对如何使 ( if ) 语句检测具有大小写的字符感到困惑。 我曾尝试在 if 语句中使用“and”,但它会太长。 我目前的输入是:

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'

程序将检查大小写字符。 如果输入全部大写,它将打印出来 有一个大机器人在排队 如果输入只有小写字母,那么它只会打印 有一个小机器人在排队。 如果输入同时包含小写和大写,它将打印: 队伍中有一个中型机器人。

【问题讨论】:

  • 你能举个中号的例子吗?你的意思是像机器人?
  • 另外,例如,您的代码是否应该适用于“机器人”,或者单词robot

标签: python


【解决方案1】:

您可以先将输入小写,然后再检查小写robot是否在输入字符串中:

变化:

elif b in a:

到:

elif 'robot' in a.lower():

【讨论】:

  • 但这并没有将ROBOTrobot 分开,这两者都会在早期的案例中被发现
  • 请阅读 OP 的代码。他的前两个if 表达式已经测试了小写和大写条件,我只是帮助他修复第三个条件,它测试混合大小写。使用elif,除非前两个表达式失败,否则不会计算第三个表达式。
  • 知道了。我不清楚你只提到第三个条件
【解决方案2】:

如何使用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.'")

【讨论】:

    【解决方案3】:

    您想使用 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.')
    

    【讨论】:

      【解决方案4】:

      试试这个:

      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']
      

      【讨论】:

        猜你喜欢
        • 2023-04-04
        • 1970-01-01
        • 2021-09-13
        • 2020-07-16
        • 2021-08-19
        • 2015-02-08
        • 2021-12-07
        • 1970-01-01
        相关资源
        最近更新 更多