使用Python减少计算字符串中出现的字符数

时间:2018-03-21 04:09:31

标签: python python-3.x

如何查找" char"存在于给定的字符串"字符串"使用python reduce函数?

我刚学习减少。它只返回一个元素。所以我认为应该有办法使用 reduce 完成这项工作。

到目前为止还没有找到。

样品:

char:'s'
inputstring:'assntcs'

output(number of occurrence of s in 'assntcs'):-3

1 个答案:

答案 0 :(得分:1)

肯定更好的方法,但如果你真的想使用reduce,你可以使用以下内容:

>>> from functools import reduce
>>> reduce(lambda x, y: x + (1 if y == 's' else 0), 'assntcs', 0)
3

如果它们是您要查找的字符,则只计算该字符串中的元素,在本例中为s

同样,这太复杂了。您只需使用count()

即可
>>> 'assntcs'.count('s')
3
相关问题