当前位置: 首页 > news >正文

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中的==代表相等的含义不同。


http://www.mrgr.cn/news/42486.html

相关文章:

  • 【Git】vscode链接github拉去镜像
  • 梗百科——信号和槽机制
  • 【高频SQL基础50题】21-25
  • 【Docker从入门到进阶】06.常见问题与解决方案 07.总结与资源
  • 民峰:助力投资者实现财务自由
  • 【LeetCode】每日一题 2024_10_4 飞机座位分配概率(数学)
  • 浅谈memset和memcpy的区别
  • C++-容器适配器- stack、queue、priority_queue和仿函数
  • 昇思MindSpore进阶教程--在ResNet-50网络上应用二阶优化实践(下)
  • 多智能体协作强化学习中的知识共享
  • 【数据库】行式存储和列式存储
  • C++游戏开发
  • Spring Boot实现新闻个性化推荐
  • 构建古典舞艺术社区:SpringBoot平台开发指南
  • [机缘参悟-228] - 一个IT人如何理解:心不死,道不生?
  • 【JAVA开源】基于Vue和SpringBoot的宠物咖啡馆平台
  • 从零开始:SpringBoot实现古典舞在线交流平台
  • ICM20948 DMP代码详解(59)
  • 【AIGC】ChatGPT开发者必备:如何获取 OpenAI 的 API Key
  • Excel数据分析!开启数据洞察之门