python如何比较字符串

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

复制代码
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模块,适合任何对象,包含的方法有:

复制代码
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)

实例

复制代码
>>> import operator
>>> operator.eq('hello', 'name');
False
>>> operator.eq('hello', 'hello');
True

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

相关推荐
常利兵1 天前
一文搞懂双Token、SSO与第三方权限打通,附实战代码
python·gitee·kotlin
认真的小羽❅1 天前
JavaScript完全指南:从入门到精通
开发语言·javascript·ecmascript
xuhaoyu_cpp_java1 天前
JAVA线程安全类
java·开发语言
香水5只用六神1 天前
【TIM】基本定时器定时实验(2)
c语言·开发语言·stm32·单片机·嵌入式硬件·mcu·学习
从零点1 天前
认识Linux和mpu开发板之间的联系
linux
BatyTao1 天前
Python从零起步-数据容器
开发语言·python
承渊政道1 天前
C++学习之旅【C++伸展树介绍以及红黑树的实现】
开发语言·c++·笔记·b树·学习·visual studio
牛十二1 天前
Ubuntu 虚拟机安装完全免费的网易有道龙虾实战流程
linux·运维·ubuntu
郭涤生1 天前
C++中设置函数与回调函数设值的性能差异及示例
开发语言·c++
yangyanping201081 天前
Linux学习三之 清空 nohup.out 文件
linux·chrome·学习