python - 字符串是如何比较的?

标签 python string comparison

我想知道 Python 如何进行字符串比较,更具体地说,当 a 小于 < 时它如何确定结果或大于 >使用运算符。

例如,如果我输入 print('abc' < 'bac')我得到 True .我知道它会比较字符串中的相应字符,但是由于没有更好的术语,它不清楚为什么会有更多的“权重”放在 a 的事实上。小于 b (第一个位置)在第一个字符串中,而不是 a小于 b在第二个字符串中(第二个位置)。

最佳答案

来自 docs :

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 Unicode code point number to order individual characters.

或在 Python 2 :

Lexicographical ordering for strings uses the ASCII ordering for individual characters.

举个例子:

>>> 'abc' > 'bac'
False
>>> ord('a'), ord('b')
(97, 98)

只要发现a 小于b,就会返回结果False。不比较其他项目(如您所见,第二个项目:b > a is True)。

注意大小写:

>>> [(x, ord(x)) for x in abc]
[('a', 97), ('b', 98), ('c', 99), ('d', 100), ('e', 101), ('f', 102), ('g', 103), ('h', 104), ('i', 105), ('j', 106), ('k', 107), ('l', 108), ('m', 109), ('n', 110), ('o', 111), ('p', 112), ('q', 113), ('r', 114), ('s', 115), ('t', 116), ('u', 117), ('v', 118), ('w', 119), ('x', 120), ('y', 121), ('z', 122)]
>>> [(x, ord(x)) for x in abc.upper()]
[('A', 65), ('B', 66), ('C', 67), ('D', 68), ('E', 69), ('F', 70), ('G', 71), ('H', 72), ('I', 73), ('J', 74), ('K', 75), ('L', 76), ('M', 77), ('N', 78), ('O', 79), ('P', 80), ('Q', 81), ('R', 82), ('S', 83), ('T', 84), ('U', 85), ('V', 86), ('W', 87), ('X', 88), ('Y', 89), ('Z', 90)]

关于python - 字符串是如何比较的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4806911/

相关文章:

ios - 如何转换颜色?

python - Beautiful Soup - 获取包含字符串的参数属性

objective-c - 比较两个 BOOL 值

bash,比较命令的输出

java - 用字符代码而不是正则表达式替换字符串?

c - 我制作的这个函数是否正确地将一个字符串附加到另一个字符串?

c# - C#字符串的$修饰符是什么

python - 我们可以通过 python 获取文件的唯一 ID 吗?

python - 在创建 pytorch NN 模块时使用列表

python - 找不到满足要求的版本,报错python