Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match a substring in a string, ignoring case

Tags:

python

perl

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) 
like image 727
Mandar Pande Avatar asked Jul 05 '11 08:07

Mandar Pande


People also ask

How do you check if a string contains another string in a case insensitive manner in Python?

Ignore case : check if a string exists in another string in case insensitive approach. Use re.search() to find the existence of a sub-string in the main string by ignoring case i.e. else return a tuple of False & empty string.

How do you check if a string ignores a case in Python?

Compare strings by ignoring case using Python As both the strings has similar characters but in different case. So to match these strings by ignoring case we need to convert both strings to lower case and then match using operator == i.e. It matched the strings in case in sensitive manner.


1 Answers

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 
like image 111
eumiro Avatar answered Sep 27 '22 16:09

eumiro