7

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
lucemia
  • 6,349
  • 5
  • 42
  • 75
DavidJB
  • 2,272
  • 12
  • 30
  • 37

2 Answers2

8
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.

Andrew_CS
  • 2,542
  • 1
  • 18
  • 38
5

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.

Adam Smith
  • 52,157
  • 12
  • 73
  • 112
  • If you want to do this, you will need to use `re.escape()` and append a `$`. – Greg Hewgill Jun 19 '14 at 18:15
  • +1 for alternative route w/ warning – Andrew_CS Jun 19 '14 at 18:16
  • @GregHewgill why would you need to do `re.escape()`? You're right about `$` though, adding that now. – Adam Smith Jun 19 '14 at 18:18
  • @AdamSmith: Well you wouldn't need it for a literal `"webcam"`, but you would need it if you're searching for something taken from user input, for example. A string like `"foo[bar"` is an invalid regex. – Greg Hewgill Jun 19 '14 at 18:28
  • @GregHewgill understood. I don't know if that's part of what the OP needs though, as his example is matching against a literal string. If so it'd be easier to do `re.match("\b"+re.escape(raw_input())+"\b", " ".join(my_list), re.I)` – Adam Smith Jun 19 '14 at 18:30