品易云推流 关闭
文章详情页
文章 > Python常见问题 > Python中如何进行字符串比较大小?

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

头像

宋雪维

2020-12-11 15:46:519913浏览 · 0收藏 · 0评论

在Python中,我们会经常使用到字串符,用于编码码字。有的时候会需要比较字符串大小。本文主要介绍Python字符串比较大小方法:字符串的比较是比较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

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

关注

关注公众号,随时随地在线学习

本教程部分素材来源于网络,版权问题联系站长!

底部广告图