首页 > 解决方案 > 如何在 Python 中使用带有布尔表达式的 count 函数

问题描述

为什么这段代码输出 2?'m' 为 0(假),那么为什么它不输出 0,因为有and表达式?

s='hello'
print(s.count('m' and 'l'))

输出:

2

标签: pythoncount

解决方案


如果你打印出来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'

推荐阅读