123

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)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mandar Pande
  • 12,250
  • 16
  • 45
  • 72

10 Answers10

215

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
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
eumiro
  • 207,213
  • 34
  • 299
  • 261
  • 2
    re.search(pattern, string, flags=0) https://docs.python.org/3/library/re.html#re.search Scan through string looking for the first location where the regular expression pattern produces a match, and return a corresponding match object. Return None if no position in the string matches the pattern; note that this is different from finding a zero-length match at some point in the string. – Miro Jul 28 '20 at 12:51
  • Be careful about special characters. They can cause problems with this method – mustafa candan Sep 19 '21 at 09:07
43

You are looking for the .lower() method:

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

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

Neuron
  • 5,141
  • 5
  • 38
  • 59
Samuele Mattiuzzo
  • 10,760
  • 5
  • 39
  • 63
24

One can use the in operator after applying str.casefold to both strings.

str.casefold is the recommended method for use in case-insensitive comparison.

Return a casefolded copy of the string. Casefolded strings may be used for caseless matching.

Casefolding is similar to lowercasing but more aggressive because it is intended to remove all case distinctions in a string. For example, the German lowercase letter 'ß' is equivalent to "ss". Since it is already lowercase, lower() would do nothing to 'ß'; casefold() converts it to "ss".

The casefolding algorithm is described in section 3.13 of the Unicode Standard.

New in version 3.3.

For case-insensitive substring search:

needle = "TEST"
haystack = "testing"
if needle.casefold() in haystack.casefold():
    print('Found needle in haystack')

For case-insensitive string comparison:

a = "test"
b = "TEST"
if a.casefold() == b.casefold():
    print('a and b are equal, ignoring case')
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
10

Try:

if haystackstr.lower().find(needlestr.lower()) != -1:
  # True
FelixSFD
  • 6,052
  • 10
  • 43
  • 117
norbertoisaac
  • 111
  • 1
  • 4
7
a = "MandY"
a_low = a.lower()
if "mandy" in a_low:
    print("true")

work around

Neuron
  • 5,141
  • 5
  • 38
  • 59
Riccardo B.
  • 354
  • 2
  • 10
4

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

pabloverd
  • 614
  • 8
  • 8
3

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

if "mandy" in line.lower():

VHS
  • 9,534
  • 3
  • 19
  • 43
3
import re
if re.search('(?i)Mandy Pande:', line):
    ...
a'r
  • 35,921
  • 7
  • 66
  • 67
2

See this.

In [14]: re.match("mandy", "MaNdY", re.IGNORECASE)
Out[14]: <_sre.SRE_Match object at 0x23a08b8>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Fredrik Pihl
  • 44,604
  • 7
  • 83
  • 130
2

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.
mpriya
  • 823
  • 8
  • 15