python中字符串怎么比较大小


本文摘自php中文网,作者尚,侵删。

Python的字符串比较与Java类似,也需要一个比较函数,而不能用==符号。用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

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如何产生20个随机整数

“if __name__ == __main__:”有什么作用

三目运算符简介

Python是什么软件下载

scrapy实现新浪微博爬虫

Python中函数赋值给变量时的问题注意详解

资深程序员Python学习进阶书籍推荐

Python 字典(dictionary)操作详解_Python

Python中转义字符是什么意思

孩子学Python有用吗

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...