在较长的字符串中查找字符串而不考虑大小写(并确定是哪种情况)

2024-05-19 07:41:25 发布

您现在位置:Python中文网/ 问答频道 /正文

一般来说,我对python和编程还比较陌生,目前正在Grok online上一门在线课程。目前我被困在第二道课上(机器人排成一排!)简而言之就是设计一个程序,读入一行文本并打印出robot这个词是否出现,尽管它必须弄清楚这个词是小写、大写还是混合大小写。到目前为止,我的解决方案是:

text = input('Line: ')

if 'robot' in text:
  print('There is a small robot in the line.')

elif 'robot'.upper() in text:
  print('There is a big robot in the line.')

elif 'robot' or 'ROBOT' != text.isupper() and not text.islower():
  print('There is a medium sized robot in the line.')

else:
  print('No robots here.')

另一件事是程序必须将这个单词作为一个单独的字符串来区分,所以它会为“robot”打印True,而为“strobotron”打印false。在


Tags: thetextin程序grokis编程line
3条回答

您的第二个elif语句应该是

elif 'robot' in text.islower() and not ('ROBOT' in text or 'robot' in text):

如果你想在一条线上完成所有这些。在

对于第二个要求,可以使用regex word boundary anchors

^{pr2}$

这样可以处理标点符号并避免匹配strobotron:

text = input('Line: ')

text = text.replace('.,?;:"', ' ')
words = text.split()
lowers = text.lower().split()

if 'robot' in words:
  print('There is a small robot in the line.')
elif 'robot'.upper() in words:
  print('There is a big robot in the line.')
elif 'robot' in lowers:
  print('There is a medium sized robot in the line.')
else:
  print('No robots here.')

我假设您的输入最多包含一个机器人字符串。在

>>> def findrobot(text):
        if 'robot' in text:
            print('There is a small robot in the line.')
        elif 'robot'.upper() in text:
            print('There is a big robot in the line.')
        elif re.search(r'(?i)robot', text):
            if 'robot' not in text and 'ROBOT' not in text:
                print('MIxed cased robot found')
        else:
            print('No robots here.')


>>> text = input('Line: ')
Line: robot
>>> findrobot(text)
There is a small robot in the line.
>>> text = input('Line: ')
Line: ROBOT
>>> findrobot(text)
There is a big robot in the line.
>>> text = input('Line: ')
Line: RobOt
>>> findrobot(text)
MIxed cased robot found
>>> text = input('Line: ')
Line: foo
>>> findrobot(text)
No robots here.

相关问题 更多 >

    热门问题