• 技术文章 >常见问题 >Python常见问题

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

    宋雪维宋雪维2020-12-11 15:46:51原创8969

    在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

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

    专题推荐:python字符串比较大小
    品易云
    上一篇:python max函数中key是如何用的? 下一篇:Python中字符串如何查找?

    相关文章推荐

    • Python中apscheduler执行使用步骤• classmethod如何在python中选择参数?• python中min函数怎么用?• 如何使用strip在python中删除?

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网