为什么('a'>'b')在Python中评估为false?

时间:2020-06-20 06:26:44

标签: python

我不知道python如何评估这个表达式,在评估这种表达式时会考虑什么?

代码段: 打印('a'>'b')

3 个答案:

答案 0 :(得分:1)

如果您比较python中的字符串,它将考虑字符的ascii值。 'a'的Ascii值为97,'b'的Ascii值为98。因此,基本上,您要问97> 98是否为假。这就是('a'>'b')评估为false的原因。

下面是一些例子

'a' > 'b' -> false
'ac' > 'ab' -> true (here first characters are equal. So it will compare 'c' and 'b')
'ac' > 'ba' -> false (here first characters are different. So it will just compare first characters)

答案 1 :(得分:0)

Python对字符串使用字典顺序。这意味着它使用Unicode点号对字符进行排序。

参考: https://docs.python.org/3/tutorial/datastructures.html#comparing-sequences-and-other-types

您可能会发现这很有用: https://en.wikipedia.org/wiki/List_of_Unicode_characters

答案 2 :(得分:0)

最好查看ASCII码表。我在下面提到了十六进制数字。

在ASCII码表中,“ a”对应于数字61,“ b”对应于数字62。

61 <62。

因此,“ print('a'>'b')”打印为false。

Ps。 “ print('a'<'b')”打印为true。 “ print('#'<'$')”也显示true。

https://simple.wikipedia.org/wiki/ASCII