Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Program to compare two strings by ignoring case
In Python, we can compare two strings while ignoring their case using several approaches. Strings are character sequences that can contain uppercase and lowercase letters. When comparing strings case-insensitively, we need to normalize both strings to the same case before comparison.
Using lower() Method
The most common approach is converting both strings to lowercase using the lower() method before comparison ?
string1 = "Hello"
string2 = "hello"
if string1.lower() == string2.lower():
print("The strings are equal, ignoring case.")
else:
print("The strings are not equal, ignoring case.")
The strings are equal, ignoring case.
Using upper() Method
Similarly, we can use the upper() method to convert both strings to uppercase ?
string1 = "PYTHON"
string2 = "python"
if string1.upper() == string2.upper():
print("The strings are equal, ignoring case.")
else:
print("The strings are not equal, ignoring case.")
The strings are equal, ignoring case.
Using casefold() Method
The casefold() method is more aggressive than lower() and handles special Unicode characters better ?
string1 = "Straße" # German word with ß
string2 = "STRASSE"
if string1.casefold() == string2.casefold():
print("The strings are equal, ignoring case.")
else:
print("The strings are not equal, ignoring case.")
The strings are equal, ignoring case.
Complex Example with Different Cases
Here's a practical example comparing sentences with mixed cases ?
string1 = "Welcome To TutorialsPoint"
string2 = "welcome to tutorialspoint"
# Method 1: Using lower()
result1 = string1.lower() == string2.lower()
# Method 2: Using upper()
result2 = string1.upper() == string2.upper()
# Method 3: Using casefold()
result3 = string1.casefold() == string2.casefold()
print(f"Using lower(): {result1}")
print(f"Using upper(): {result2}")
print(f"Using casefold(): {result3}")
Using lower(): True Using upper(): True Using casefold(): True
Comparison of Methods
| Method | Best For | Unicode Support |
|---|---|---|
lower() |
Basic ASCII text | Good |
upper() |
Basic ASCII text | Good |
casefold() |
International text | Excellent |
Conclusion
Use lower() or upper() for basic case-insensitive string comparisons. For international text with special Unicode characters, casefold() provides the most reliable results. This technique is essential for user input validation and text processing applications.
