[python] How to match a substring in a string, ignoring case

I'm looking for ignore case string comparison in Python.

I tried with:

if line.find('mandy') >= 0:

but no success for ignore case. I need to find a set of words in a given text file. I am reading the file line by line. The word on a line can be mandy, Mandy, MANDY, etc. (I don't want to use toupper/tolower, etc.).

I'm looking for the Python equivalent of the Perl code below.

if ($line=~/^Mandy Pande:/i)

This question is related to python perl

The answer is


If you don't want to use str.lower(), you can use a regular expression:

import re

if re.search('mandy', 'Mandy Pande', re.IGNORECASE):
    # Is True

You can use in operator in conjunction with lower method of strings.

if "mandy" in line.lower():


See this.

In [14]: re.match("mandy", "MaNdY", re.IGNORECASE)
Out[14]: <_sre.SRE_Match object at 0x23a08b8>

you can also use: s.lower() in str.lower()


Try:

if haystackstr.lower().find(needlestr.lower()) != -1:
  # True

There's another post here. Try looking at this.

BTW, you're looking for the .lower() method:

string1 = "hi"
string2 = "HI"
if string1.lower() == string2.lower():
    print "Equals!"
else:
    print "Different!"

import re
if re.search('(?i)Mandy Pande:', line):
    ...

a = "MandY"
alow = a.lower()
if "mandy" in alow:
    print "true"

work around