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')
Java String equalsIgnoreCase() Method The equalsIgnoreCase() method compares two strings, ignoring lower case and upper case differences.
Approach No 1: Python String lower() Method This is the most popular approach to case-insensitive string comparisons in Python. The lower() method converts all the characters in a string to the lowercase, making it easier to compare two strings.
A function is not "case sensitive". Rather, your code is case sensitive. The way to avoid this problem is to normalize the input to a single case before checking the results. One way of doing so is to turn the string into all lowercase before checking.
The equalsIgnoreCase() method of the String class is similar to the equals() method the difference if this method compares the given string to the current one ignoring case.
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):
This if you're doing exact comparison.
if choice.lower() == "power":
Or this, if you're doing substring comparison.
if "power" in choice.lower():
You also have choice.lower().startswith( "power" )
if that interests you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With