• 技术文章 >Python技术 >Python基础教程

    python如何比较字符串

    爱喝马黛茶的安东尼爱喝马黛茶的安东尼2019-10-26 15:13:33原创12714

    Python可使用cmp()方法来比较两个对象,相等返回 0 ,前大于后,返回 1,小于返回 -1。

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    a = "abc"

    b = "abc"

    c = "aba"

    d = "abd"

    print cmp(a,b)

    print cmp(a,c)

    print cmp(a,d)

    //返回

    0

    1

    -1

    相关推荐:《Python视频教程

    Python3.X 的版本中已经没有cmp函数,如果你需要实现比较功能,需要引入operator模块,适合任何对象,包含的方法有:

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    operator.lt(a, b)

    operator.le(a, b)

    operator.eq(a, b)

    operator.ne(a, b)

    operator.ge(a, b)

    operator.gt(a, b)

    operator.__lt__(a, b)

    operator.__le__(a, b)

    operator.__eq__(a, b)

    operator.__ne__(a, b)

    operator.__ge__(a, b)

    operator.__gt__(a, b)

    实例

    1

    2

    3

    4

    5

    >>> import operator

    >>> operator.eq('hello', 'name');

    False

    >>> operator.eq('hello', 'hello');

    True

    注意:python3中使用==可进行比较两个字符串,与java中的==代表相等的含义不同。

    专题推荐:python 比较 字符串
    上一篇:python交互式命令时如何清除 下一篇:python全栈开发是什么?

    相关文章推荐

    • python如何判断字符串相等• python3中怎么比较字符串是否相等

    全部评论我要评论

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

  • 取消发布评论
  • 

    Python学习网