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

发布时间:2022-05-18 09:47:17 人气:1298 作者:多测师

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

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

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

  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中如何进行字符串比较大小?希望对大家有所帮助,如果想要了解更多Python相关知识,请关注多测师。https://www.e70w.com/xwzx/


返回列表
在线客服
联系方式

热线电话

17727591462

上班时间

周一到周五

二维码
线