【问题标题】:How to check if a random mixed case word is in a string如何检查随机混合大小写的单词是否在字符串中
【发布时间】:2020-05-19 09:43:57
【问题描述】:

我正在尝试检查一行中是否有机器人一词。 (我正在学习 python。对它还是很陌生。)如果“机器人”这个词在一行中,它会打印出一些东西。与“机器人”相同。但是,我需要知道当机器人在线但在随机混合情况下如何输出,例如 rObOt。这可能吗?看来我需要写出每个组合。我正在使用 Python 3。谢谢 :)。

if ' robot ' in line:
  print("There is a small robot in the line.")
elif ' ROBOT ' in line:
  print("There is a big robot in the line.")
elif 'rOBOt' in line:
  print("There is a medium sized robot in the line.")
else:
  print("No robots here.")

【问题讨论】:

  • 使用lower() 将整行转换为小写,然后检查robot。找出 robot 是否是一个独立的词有点困难,最好使用带有词边界的正则表达式来解决。
  • .lower() 两者并进行比较。

标签: python string lowercase capitalization mixed-case


【解决方案1】:

您可以使用lower(),这是一种字符串方法,可以在 Python 中将字符串转换为小写。

所以这个想法是在你检查了小写和大写之后,如果在任意情况下有一个机器人,它将在第三个条件下被拾取。

if ' robot ' in line:
  print("There is a small robot in the line.")
elif ' ROBOT ' in line:
  print("There is a big robot in the line.")
elif ' robot ' in line.lower():
  print("There is a medium sized robot in the line.")
else:
  print("No robots here.")

另外,我注意到您在单词robot 之前和之后放置了一个空格,我猜您也想为第三个条件放置一个空格。

【讨论】:

  • 如果机器人在行尾怎么办? Doomo arigatoo Mr. Robot!
  • 好问题。我认为这取决于他想检查什么。正则表达式也可能是一个很好的工具。
【解决方案2】:

希望下面的代码可以帮助到你。

line = "Hello robot RoBot ROBOT"

l = line.split(" ")

exist = False

for word in l:
    if word.upper() == "ROBOT":

        exist = True

        if word.isupper():
            print("There is a big robot in the line.")
        elif word.islower():
            print("There is a small robot in the line.")
        else:
            print("There is a medium sized robot in the line.")

if not exist:
    print("No robots here.")

【讨论】:

  • 特别是当 OP 声明它们是 Python 的新手时,您的回答将受益于一点解释。还有,为什么使用exist 而不是简单的else
猜你喜欢
  • 2012-01-03
  • 1970-01-01
  • 2012-07-20
  • 2017-01-11
  • 2010-10-15
  • 1970-01-01
  • 1970-01-01
  • 2020-07-16
  • 2014-05-04
相关资源
最近更新 更多