Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make string check case insensitive?

Tags:

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') 
like image 343
Jack Avatar asked May 04 '11 21:05

Jack


People also ask

How do I make my string not case-sensitive?

Java String equalsIgnoreCase() Method The equalsIgnoreCase() method compares two strings, ignoring lower case and upper case differences.

How do you make a string check case insensitive in Python?

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.

How do you make a function case insensitive?

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.

How do you compare strings case insensitive?

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.


2 Answers

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): 
like image 69
Tim Pietzcker Avatar answered Sep 17 '22 13:09

Tim Pietzcker


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.

like image 35
S.Lott Avatar answered Sep 20 '22 13:09

S.Lott