Comparing Strings in Python

In Python, strings can be compared using various comparison operators. These comparisons are based on the lexicographical order of the characters in the strings, which follows the Unicode value of each character.

1. Using Comparison Operators

You can use the following comparison operators to compare strings:

Code Example

# Comparing strings using different operators
        
        string1 = "apple"
        string2 = "banana"
        string3 = "apple"
        
        # Equality and inequality
        print("string1 == string2:", string1 == string2)  # False
        print("string1 != string2:", string1 != string2)  # True
        
        # Lexicographical comparisons
        print("string1 < string2:", string1 < string2)    # True
        print("string1 > string2:", string1 > string2)    # False
        print("string1 <= string3:", string1 <= string3)  # True
        print("string1 >= string3:", string1 >= string3)  # True

Output

string1 == string2: False
string1 != string2: True
string1 < string2: True
string1 > string2: False
string1 <= string3: True
string1 >= string3: True

Explanation

In this example, we compare the strings string1 and string2:

---

2. Case Sensitivity in String Comparisons

String comparisons in Python are case-sensitive. This means that uppercase and lowercase letters are treated as different characters.

Code Example for Case Sensitivity

# Case sensitivity in string comparisons
        
        stringA = "hello"
        stringB = "Hello"
        
        # Comparing with different cases
        print("stringA == stringB:", stringA == stringB)  # False
        print("stringA.lower() == stringB.lower():", stringA.lower() == stringB.lower())  # True

Output

stringA == stringB: False
stringA.lower() == stringB.lower(): True

Explanation

Here, stringA and stringB differ in case. The comparison returns False for case-sensitive equality. However, converting both strings to lowercase allows for a successful comparison, returning True.

---

3. String Comparison Using the cmp() Function (Python 2.x)

In Python 2.x, you can use the cmp() function to compare two strings. It returns:

Note: The cmp() function is not available in Python 3.x. Use comparison operators instead.

Code Example for cmp() Function (Python 2.x)

# Python 2.x only
        # Comparing strings using cmp()
        
        stringX = "apple"
        stringY = "banana"
        
        # Using cmp()
        print("cmp(stringX, stringY):", cmp(stringX, stringY))  # Output: -1

Output

cmp(stringX, stringY): -1

Conclusion

Comparing strings in Python can be done using various comparison operators, considering case sensitivity and lexicographical order. Understanding these comparisons is essential for string manipulation and validation in your Python programs.