Comparação lexicográfica de Python

# Note that a string x is lexicographically smaller than string y 
# if x comes before y in dictionary order, that is, 
#    either x is a prefix of y, 
#    or if i is the first position such that x[i] != y[i], 
#          then x[i] comes before y[i] in alphabetic order
from operator import lt, gt

def compare(string1, string2, less=True):
    op = lt if less else gt
    for char1, char2 in zip(string1, string2):
        ordinal1, ordinal2 = ord(char1), ord(char1)
        if ordinal1 == ordinal2:
            continue
        else:
            return op(ordinal1, ordinal2)
    return op(len(string1), len(string2))
Muddy Moose