字符串比较在python上是如何工作的?

2024-07-02 09:57:32 发布

您现在位置:Python中文网/ 问答频道 /正文

Possible Duplicate:
String Comparison Technique Used by Python

>>> "spam" < "bacon"
False
>>> "spam" < "SPAM"
False
>>> "spam" < "spamalot"
True
>>> "Spam" < "eggs"
True

问题:如何比较等长字符串。如果字符串的长度不一样,为什么“垃圾邮件”比“鸡蛋”少呢?在


Tags: 字符串falsetruestringbyspamcomparisonused
3条回答

词汇上。在

比较第一个字节,如果第一个字节的序数值小于第二个字节的序数值,那么它就更小。如果它更多,它就更大。如果它们相同,则尝试下一个字节。如果都是领带,一条长一点,短一点的就少一点。在

>>> "a" < "zzz"
True
>>> "aaa" < "z"
True
>>> "b" < "a"
False
>>> "abc" < "abcd"
True
>>> "abcd" < "abce"
True
>>> "A" < "a"
True
>>> ord("A")
65
>>> ord("a")
97

由于ASCII表中Aa之前,因此Spam中的S被认为小于eggs中的e。在

>>> "A" < "a"
True
>>> "S" < "e"
True
>>> "S" < "eggs"
True

请注意,在比较中不考虑字符串长度。正如@MikeGraham在下面的注释中正确指出的那样,从第一个字节开始比较每个字节的顺序值。 一旦发现不匹配,就会停止比较,并返回比较值,如上一个示例所示。在

来自docs - Comparing Sequences and Other Types

The comparison uses lexicographical ordering: first the first two items are compared, and if they differ this determines the outcome of the comparison; if they are equal, the next two items are compared, and so on, until either sequence is exhausted.

同样在同一段中:

Lexicographical ordering for strings uses the ASCII ordering for individual characters

Python中的字符串是lexicographically ordered,因此可以对它们进行逻辑排序:

>>> print sorted(['spam','bacon','SPAM','spamalot','Spam','eggs'])
['SPAM', 'Spam', 'bacon', 'eggs', 'spam', 'spamalot']

unicode的主要缺点是。字母é将在字母zfor example之后排序:

^{pr2}$

幸运的是,您可以使用sort函数,使用locale或string的子类对字符串进行排序。在

相关问题 更多 >