I'm trying to find a match value from a keyword using python. My values are stored in a list (my_list
) and in the below example I'm trying to find the word 'Webcam'. I only want to return the word if it is fully matched.
Using item.find works but only if the case matches (i.e. upper and lower case must be correct). But I want to return the item regardless of the case, However, I do not wish to match all instances of the string like 'Webcamnew' so using the any() method won't work I think. Does anyone know how to do this..?
my_list = ['webcam', 'home', 'Space', 'Maybe later', 'Webcamnew']
for item in my_list:
if item.find("Webcam") != -1:
print item
Python String equals case-insensitive check Sometimes we don't care about the case while checking if two strings are equal, we can use casefold() , lower() or upper() functions for case-insensitive equality check.
The casefold() method works similar to lower() method. But compared to lower() method it performs a strict string comparison by removing all case distinctions present in the string.
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.
my_list = ['webcam', 'home', 'Space', 'Maybe later', 'Webcamnew']
for item in my_list:
if 'webcam' == item.lower()
print item.lower()
Note: Strings are immutable in Python
- it doesn't modify the string in the list.
If for some reason you REALLY need to compare case insensitive strings (rather than generating a same-case string) you can use regular expressions with the re.IGNORECASE
flag. This is a terrible idea for what you seem to be trying to do, but the code is:
import re
my_list = ['webcam', 'home', 'Space', 'Maybe later', 'Webcamnew']
for item in my_list:
if re.match("webcam$",item, flags=re.I): # re.I == re.IGNORECASE
print item
The reason this is a Bad Idea is that using regular expressions for simple matching is kind of like using a backhoe to dig post holes. Sure, you can do it, but it's expensive, time-consuming, and has the opportunity to introduce errors you didn't think about until you accidentally swung the boom through your living room window.
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