我正在尝试检查一行中是否有机器人这个词。 (我正在学习python。它仍然很新。)如果单词“ robot”排成一行,它将打印出一些内容。与“机器人”相同。但是,我需要知道当机器人在生产线中但在随机混合的情况下(例如rObOt)时如何输出。这可能吗?似乎我需要写出每个组合。我正在使用Python3。谢谢:)。
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()
,这是一种字符串方法,可以在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
之前和之后都留了一个空格,我想您也想为第三个条件放置一个空格。