-1

I have two strings, Right and banana. When I compare, Right < banana the result is given as True. I understand that Python compares letter by letter.

(1) But then these two strings are not in the same length. How would this be possible? (2) I looked up the ASCII, then I tried the following: R < b, and the result is True; i < a, and the result is False, and so on. Clearly we have False and True in comparing letter by letter, Right < banana. How does Python determine that the final result is True?

I did look up a few sources online, and couldn't find answer. I've just started to learn Python as my first programming language, so maybe I didn't know where to look...

Rajnish
  • 419
  • 6
  • 21
Huy Truong
  • 148
  • 1
  • 8

2 Answers2

5

Python compares sequences naively. Since "R" is less than "b", "Right" is less than "banana".

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • In the ascii table, you first have all uppercase letters, then all lowercase letters. So r > b, but R < b. – Bartez Jan 10 '16 at 20:49
0

Python uses the ASCII/Byte/Unicode point value to compare chars For example

def python_less_than(s1, s2):
    'a function that acts like the way python compare strings'
    return [ord(c) for c in s1] < [ord(c) for c in s2]
Yoav Glazner
  • 7,936
  • 1
  • 19
  • 36