2

I have written this code in python 3.5

x="absx"
o="abcdef"

and if i am doing this operation,

x<o
False   #it return's False and i think it should return True

So what is '<' doing in case of strings and why is it not returning true. how is it comparing x and o?

Anshul Goyal
  • 73,278
  • 37
  • 149
  • 186
Iamstr1ng
  • 23
  • 6
  • 2
    Strings are compared by the order they would appear in a regular dictionary. Your `o` string would be before your `x` string in a dictionary, so `o < x` is True. See [Lexicographical order](https://en.wikipedia.org/wiki/Lexicographical_order). – PM 2Ring Oct 14 '16 at 14:17

2 Answers2

3

The < or > would result in lexicographic comparison of the two strings:

>>> x="absx"
>>> o="abcdef"
>>> x > o
True

Lexicographic ordering is same as dictionary ordering, and basically, the operators are checking for which string would come earlier (or later) in a dictionary order. The behavior is same for both Python 2 and 3.

The final result does not depend on the size of the string, Example:

>>> "a" < "aaaaa" 
True

In example above "a" would come before "aaaaa" when written in dictionary order. To compare by length of strings, use the len() function on the strings.

Anshul Goyal
  • 73,278
  • 37
  • 149
  • 186
0

Lexicographic comparison. In your case o would come after x.

Just Rudy
  • 700
  • 11
  • 28