How to make string check case insensitive?

Jack picture Jack · May 4, 2011 · Viewed 42.9k times · Source

I've started learning Python recently and as a practise I'm working on a text-based adventure game. Right now the code is really ineffective as it checks the user responce to see if it is the same as several variations on the same word. How do I change it so the string check is case insensitive?

Example code below:

if str('power' and 'POWER' and 'Power') in str(choice):
    print('That can certainly be found here.')
    time.sleep(2)
    print('If you know where to look... \n')

Answer

Tim Pietzcker picture Tim Pietzcker · May 4, 2011
if 'power' in choice.lower():

should do (assuming choice is a string). This will be true if choice contains the word power. If you want to check for equality, use == instead of in.

Also, if you want to make sure that you match power only as a whole word (and not as a part of horsepower or powerhouse), then use regular expressions:

import re
if re.search(r'\bpower\b', choice, re.I):