2
print 'Python' > 'python'  # equals False
print 'python' > 'Python'  # equals True

Can someone please explain how this is interpreted since p is smaller case then then capital P? But yet p is always greater then P.

Tested on Python 2.7

William J
  • 29
  • 1
  • 2
  • 1
    The ASCII value of `p` is 112. `P` is 80. – jsheeran Jun 02 '17 at 13:42
  • 1
    I use http://www.asciitable.com/ to check ascii values of characters. – quamrana Jun 02 '17 at 14:02
  • 1
    It may seem backwards that lowercase letters are greater than uppercase, but that's due to historical reasons: the earliest encodings only had uppercase letters. Lowercase letters were added decades later, and naturally they were added to the ends of the existing character tables for backwards compatibility. – PM 2Ring Jun 02 '17 at 14:26

2 Answers2

3

String comparison in Python is case-sensitive and conventionally uppercase characters go before lowercase characters.

Python compares strings lexicographically, using the constituent characters based on their ASCII or Unicode code points. The same principle applies for Python3.

In ASCII, and therefore in Unicode, lowercase letters are greater than all uppercase letters. Therefore, 'p' > 'P', and indeed, 'a' > 'Z'. In your case, "python" begins with the letter 'p', whereas "Python" begins with the uppercase letter 'P'. They begin with different code points; the lowercase variant is greater.

The convention that lowercase letters are greater than uppercase letters in ASCII is historical.

0

It may have something to do with the unicode values of the letters.

>>> ord('p')
112
>>> ord('P')
80

112 > 80, therefore 'p' > 'P'

njoosse
  • 549
  • 3
  • 8