Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match string in python regardless of upper and lower case differences [duplicate]

Tags:

python

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
like image 941
DavidJB Avatar asked Jun 19 '14 18:06

DavidJB


People also ask

How do you compare two strings irrespective of a case in Python?

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.

How do you compare lower and upper case in Python?

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.

How do you make a search 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.


2 Answers

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.

like image 138
Andrew_CS Avatar answered Nov 14 '22 22:11

Andrew_CS


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.

like image 40
Adam Smith Avatar answered Nov 15 '22 00:11

Adam Smith