-6

How does python compare strings via the inequality operators?

a = "cat"
b = "dog"

a < b
True

What properties of the strings results in a < b == True?

I've tried few other examples but still have no idea how Python compares them. Does Python compares strings like integers?

user107224
  • 205
  • 2
  • 12
smougie
  • 1
  • 2

1 Answers1

1

Because python compares sequences (i.e. strings you have) sequentially by element values. "c" comes before "d" in Unicode, hence the result.

To compare length, use

len(a) == len(b)

The motivation behind this – having sequential comparison of elements, you can sort sequences in sane way. I.e. sorting list of names alphabetically is just sorted(names_list). And this works exactly because strings will be compared alphabetically and sequentially.

Slam
  • 8,112
  • 1
  • 36
  • 44