Python中如何进行字符串比较大小?

美女程序员鼓励师

在Python中,我们会经常使用到字串符,用于编码码字。有的时候会需要比较字符串大小。本文主要介绍Python字符串比较大小" title="字符串比较大小">字符串比较大小方法:字符串的比较是比较ASCII码值 ,哪个值大哪个字符串就大。另外也可通过内置函数 ord() 获得每个字符的 Unicode 编码进行大小比较。

python字符串之间用比较符实际上就是比较第一个字母的ASCII码大小

str1 = "abc";

str2 = "xyz";

str1>str2

true

通过内置函数 ord() 获得每个字符的 Unicode 编码进行大小比较

print(max(['1', '2', '3']))  # 3

print(max(['31', '2', '3']))  # 31

print(max(['13', '2', '3']))  # 3

print(max(['10', '11', '12']))  # 12

print(max(['13', '11', '12']))  # 13

print(ord('1'))  # 49

print(ord('2'))  # 50

print(ord('3'))  # 51

# print(ord('10')) TypeError: ord() expected a character, but string of length 2 found

print(ord(' '))  # 32

以上比较字符串大小的方法啦,大家可以直接套用公式使用哦~

以上是 Python中如何进行字符串比较大小? 的全部内容, 来源链接: utcz.com/z/541735.html

回到顶部