0

I am trying to check to see if there is the word robot in a line. (I'm learning python. Still very new to it.) If the word 'robot' is in a line it prints something out. Same with 'ROBOT'. However, I need to know how to output when robot is in the line but in a randomly mixed case, eg rObOt. Is this possible? It seems like I would need to write out every combination. I'm using Python 3. Thanks :).

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.")
finalerock44
  • 65
  • 2
  • 11
  • Use `lower()` to convert the entire line to lowercase and then just check for `robot`. Finding out whether `robot` is a standalone word is a little bit harder, and is probably best solved using a regular expression with word boundaries. – Robby Cornelissen May 19 '20 at 09:46
  • `.lower()` both and compare then. – Klaus D. May 19 '20 at 09:46

2 Answers2

2

You can use lower() which is a string method to convert a string to lowercase in Python.

So the idea is after you check for small case and capital case, if there is a robot in arbitrary case, it will be picked up in the third condition.

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.")

Also, I notice that you place a space before and after the word robot, I am guessing you would like to place a space for the third condition as well.

Siong Thye Goh
  • 3,518
  • 10
  • 23
  • 31
1

Hope the code below can help you.

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.")
Albert Nguyen
  • 377
  • 2
  • 11
  • 1
    Particularly as the OP has stated that they are new to Python, your answer would benefit from a little explanation. Also, why the use of `exist` rather than simple `else`? – David Buck May 19 '20 at 10:03