3

What does string comparison do in Python (and in general)? If I have the following code:

def com(a):
    if a > 'banana':
        print 'yes'
    else:
        print 'no'

What would make a "greater than" 'banana'? I'm a bit confused by the concept of "comparison". What is being compared?

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
user1691278
  • 1,751
  • 1
  • 15
  • 20
  • 6
    in general, that would be a lexicographic comparison. "A"<"B", "AA"<"AB", "ALPHA">"ALPGZ" – John Dvorak Oct 13 '13 at 04:29
  • http://stackoverflow.com/questions/4806911/string-comparison-technique-used-by-python has a good answer – Hari Menon Oct 13 '13 at 04:32
  • Therefore, is the lexicograhpic order "reversed"? For example, 'zzzzzzz' would be in fact 'greater than' 'banana'? – user1691278 Oct 13 '13 at 04:33
  • 1
    I don't know what you mean by "reversed", but "zzzz" compares as greater than "banana" in most languages with string comparison – John Dvorak Oct 13 '13 at 04:34
  • Lexicographic order is a generalization of alphabetical order. Think the order of words in a dictionary. The comparison tells you which word appears before the other in an English dictionary. – Adam Oct 13 '13 at 04:37
  • yes, `'zzzzzzz' > 'banana'` – Adam Oct 13 '13 at 04:41

1 Answers1

2

It does a lexicographical string comparison.

a > b

will resolve to:

a.__gt__(b)

in this case a is of type str, so it actually calls str.__gt__(b) with a as the bound instance. "gt" stands for "greater than".

x.__gt__(y) returns True if x is greater than y as defined by the function. If gt is not defined, it will fall back to using a.__cmp__(b). which returns -1, 0, 1 depending on the comparison result. If __cmp__ is not defined for type of a, this will result in a syntax error.

str has a __gt__ method so it is used for resolving a > b. You can supply this method for any of your custom objects.

See docs about rich comparisons lt, le, eq, ne, gt, ge and also cmp.

Preet Kukreti
  • 8,417
  • 28
  • 36