python - 如何在 Python 中使用带有布尔表达式的 count 函数
问题描述
为什么这段代码输出 2?'m' 为 0(假),那么为什么它不输出 0,因为有and
表达式?
s='hello'
print(s.count('m' and 'l'))
输出:
2
解决方案
如果你打印出来print('m' and 'l')
,你会意识到它会返回l
。
Python 返回False
一个空字符串,True
其他任何东西。
当您对字符串执行布尔运算时,该and
操作返回最右边的元素,并且该or
操作返回最左边的元素。(查看 Python 中字符串的逻辑运算符)
您可以尝试更复杂的示例:
s='helllmmko'
print(s.count('k' and 'm' and 'l')) # prints count of 'l'
print(s.count('k' or 'm' or 'l')) # prints count of 'k'
print(s.count('k' and 'm' or 'l')) # prints count of 'm'
推荐阅读
- php - 声明变量 MySQL
- django - Celery 在我的 Django 项目中找不到模块
- unit-testing - 从 FileInfo.FromFileName() 返回时,添加到 MockFileSystem 的文件没有 Exists = true
- java - 列出 Azure 中(子)目录中的所有文件
- javascript - 为什么 addEventListener 在 nodejs 的 jsdom 模块中不起作用
- r - ggplot2 - 如何让两个不同直方图的箱匹配?
- python-2.7 - 为什么 Canopy 上的 opencv 在我尝试安装时会降级 numpy、scipy 和其他软件包?
- jquery - dataTable 没有加载 php bootstrap
- css - 显示网格 - 背景在右侧有一个白色间隙
- php - TYPO3 9.5.1 发布后的功能测试问题