harold232
harold232

Reputation: 119

How to make a function that counts the number of substrings in a string?

Define a function named how_many_substr_of_string(...) which receives two parameters, the first parameters is a list with strings (name it listst) and the second parameter is a single string (name it st). The function should return a number, indicating how many of the strings in the list listst are substrings in the string st

As an example, the following code fragment:

listst = ["a","bc","dd"]
st = "abc"
res = how_many_substr_of_string(listst,st)
print (res)

should produce the output: 2

My code:

def how_many_substr_of_string(listst, st):
    return listst.count(st)

My code does not work for the following conditions and any other related conditions:

listst = ["a","bc","dd"]
st = "abc"
res = how_many_substr_of_string(listst,st)
print (res)

I get the output 0 but its supposed to be 2. How to fix this or edit my code such that it will work for this any other case as shown in the question

Upvotes: 0

Views: 266

Answers (2)

Sid
Sid

Reputation: 2189

Use this:

listst = ["a","bc","dd"]
s = "abc"
def how_many_substr(iterable, st):
    res = 0
    for i in iterable:
        if i in st: res += 1
    return res
print(how_many_substr(listst, s))

Output:

2

Your code was:

def how_many_substr_of_string(listst, st):
    return listst.count(st)

This counts the number of times st occurs in listst, which is 0.

Upvotes: 0

seymourgoestohollywood
seymourgoestohollywood

Reputation: 1167

def how_many_substr_of_string(listst, st):
    return sum(1 for item in listst if item in st)

A note on why this works even though strings are considered arrays - Python will use __contains__(self, item), __iter__(self), and __getitem__(self, key) in that order to determine whether an item lies in a given string.

Upvotes: 2

Related Questions