Muthuraj
Muthuraj

Reputation: 41

using Python reduce Count the number of occurrence of character in string

How to find number of "char " present in given string "string" using python reduce function?

i just learning about reduce. It will return only one element. so i am thinking there should be way to get this done using reduce.

Didn't find any so far.

Sample:

char:'s'
inputstring:'assntcs'

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

Upvotes: 0

Views: 2372

Answers (1)

user3483203
user3483203

Reputation: 51155

There are definitely better ways to do this, but if you really want to use reduce you can use the following:

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

This simply counts the elements in that string if they are the character you are looking for, in this case, s

Again, this is overly complicated. You could simply use count():

>>> 'assntcs'.count('s')
3

Upvotes: 4

Related Questions