String comparison technique used by Python

前端 未结 7 1974
心在旅途
心在旅途 2020-11-21 15:50

I\'m wondering how Python does string comparison, more specifically how it determines the outcome when a less than (<) or greater than (>) op

7条回答
  •  盖世英雄少女心
    2020-11-21 16:06

    Python string comparison is lexicographic:

    From Python Docs: http://docs.python.org/reference/expressions.html

    Strings are compared lexicographically using the numeric equivalents (the result of the built-in function ord()) of their characters. Unicode and 8-bit strings are fully interoperable in this behavior.

    Hence in your example, 'abc' < 'bac', 'a' comes before (less-than) 'b' numerically (in ASCII and Unicode representations), so the comparison ends right there.

提交回复
热议问题