81
votes

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)
9

9 Answers

158
votes

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
29
votes

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!"
6
votes

Try:

if haystackstr.lower().find(needlestr.lower()) != -1:
  # True
5
votes
a = "MandY"
alow = a.lower()
if "mandy" in alow:
    print "true"

work around

4
votes

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

3
votes

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

if "mandy" in line.lower():

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

See this.

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

If it is a pandas series, you can mention case=False in the str.contains

data['Column_name'].str.contains('abcd', case=False) 

OR if it is just two string comparisons try the other method below

You can use casefold() method. The casefold() method ignores cases when comparing.

firstString = "Hi EVERYONE"
secondString = "Hi everyone"

if firstString.casefold() == secondString.casefold():
    print('The strings are equal.')
else:
    print('The strings are not equal.')

Output:

The strings are equal.