Python Program to Compare two strings lexicographically

We can compare two strings lexicographically in Python using comparison operators like <, >, ==, <=, and >=. Lexicographic comparison is the process of comparing two strings based on their alphabetical order, similar to how words are arranged in a dictionary.

Algorithm

A generalized algorithm to compare two strings lexicographically is as follows ?

  • Initialize two strings with the values to be compared.

  • Compare the first character of both strings. If they are equal, move to the next character and repeat. If they are not equal, proceed to step 3.

  • Determine which character comes first alphabetically. The string with the character that comes first in the alphabet will be considered "smaller" lexicographically.

Using Comparison Operators

Python provides builtin comparison operators that handle lexicographic comparison automatically. This is the most straightforward approach ?

string1 = "apple"
string2 = "banana"

if string1 < string2:
    print(f"'{string1}' comes before '{string2}'")
elif string1 > string2:
    print(f"'{string2}' comes before '{string1}'")
else:
    print("The two strings are equal")
'apple' comes before 'banana'

Manual Character-by-Character Comparison

We can also implement lexicographic comparison manually by comparing characters one by one ?

def lexicographic_compare(str1, str2):
    min_length = min(len(str1), len(str2))
    
    for i in range(min_length):
        if str1[i] < str2[i]:
            return f"'{str1}' comes before '{str2}'"
        elif str1[i] > str2[i]:
            return f"'{str2}' comes before '{str1}'"
    
    # If all compared characters are equal, check lengths
    if len(str1) < len(str2):
        return f"'{str1}' comes before '{str2}'"
    elif len(str1) > len(str2):
        return f"'{str2}' comes before '{str1}'"
    else:
        return "The two strings are equal"

# Test with different examples
print(lexicographic_compare("apple", "banana"))
print(lexicographic_compare("cat", "car"))
print(lexicographic_compare("hello", "hello"))
'apple' comes before 'banana'
'car' comes before 'cat'
The two strings are equal

Comparing Equal Strings

When two strings are identical, they are considered lexicographically equal ?

string1 = "python"
string2 = "python"

if string1 == string2:
    print("The strings are lexicographically equal")
else:
    print("The strings are not equal")

# Using other comparison operators
print(f"string1 <= string2: {string1 <= string2}")
print(f"string1 >= string2: {string1 >= string2}")
The strings are lexicographically equal
string1 <= string2: True
string1 >= string2: True

Case Sensitivity

Lexicographic comparison in Python is casesensitive. Uppercase letters come before lowercase letters in ASCII order ?

string1 = "Apple"
string2 = "apple"

print(f"'{string1}' < '{string2}': {string1 < string2}")
print(f"'{string1}' > '{string2}': {string1 > string2}")

# For case-insensitive comparison
print(f"Case-insensitive: {string1.lower() == string2.lower()}")
'Apple' < 'apple': True
'Apple' > 'apple': False
Case-insensitive: True

Practical Example

Here's a practical example that sorts a list of strings lexicographically ?

words = ["banana", "apple", "cherry", "date", "elderberry"]

# Sort lexicographically
sorted_words = sorted(words)
print("Sorted words:", sorted_words)

# Find the lexicographically smallest and largest
print(f"Smallest: {min(words)}")
print(f"Largest: {max(words)}")
Sorted words: ['apple', 'banana', 'cherry', 'date', 'elderberry']
Smallest: apple
Largest: elderberry

Conclusion

Python's builtin comparison operators provide an easy way to compare strings lexicographically. Use <, >, and == operators for simple comparisons, or implement manual characterbycharacter comparison when you need more control over the process.

Updated on: 2026-03-27T07:28:11+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements