How to match a substring in a string, ignoring case

Mandar Pande picture Mandar Pande · Jul 5, 2011 · Viewed 125.5k times · Source

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)

Answer

eumiro picture eumiro · Jul 5, 2011

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