Python使用的字符串比较技术 [英] String Comparison Technique Used by Python
问题描述
我想知道Python如何进行字符串比较,更具体地说,当使用小于(<)或大于(>)的符号时,如何确定结果。
I'm wondering how Python does string comparison, more specifically how it determines the outcome when a less than (<) or greater than (>) sign is used.
例如,如果我把print('abc'<'bac')我成真。我理解它比较字符串中的相应字符,但是它不清楚为什么有更多,由于缺乏一个更好的术语,权重放在事实上a小于b(第一个位置)在第一个字符串,而不是
For instance if I put print('abc' < 'bac') I get true. I understand that it compares corresponding characters in the string, however its unclear as to why there is more, for lack of a better term, "weight" placed on the fact that a is less than b (first position) in first string rather than the fact that a is less than b in the second string (second position).
推荐答案
从文档:
比较使用字典
排序:首先比较前两个项目
,如果它们不同,则
确定
比较的结果;如果它们相等,则接下来两个项目的
被比较,因此
打开,直到序列是
耗尽。
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.
还有:
字符串的词典排序
使用单个
字符的ASCII排序
Lexicographical ordering for strings uses the ASCII ordering for individual characters.
例如:
>>> 'abc' > 'bac'
False
>>> ord('a'), ord('b')
(97, 98)
a 一旦发现小于
b <>,则返回结果
False
/ code>。其他项目没有比较(正如你可以看到的第二个项目: b
> a
是 True
)。
The result False
is returned as soon as a
is found to be less than b
. The further items are not compared (as you can see for the second items: b
> a
is True
).
这篇关于Python使用的字符串比较技术的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!