Okay, don't laugh. I'm very new to python. Actually to programming all together. I'm doing an exercise where i have to count the number of a string in a word. Ex: count("is", "Mississippi") would be 2. I tried using string.find and was having no luck. So i tried to go back to the basics and use count. I can get it to pass 3/5 of the doctests. This is where i'm at:
def count(sub, s):
"""
>>> count('is', 'Mississippi')
2
>>> count('an', 'banana')
2
>>> count('ana', 'banana')
2
>>> count('nana', 'banana')
1
>>> count('nanan', 'banana')
0
"""
count = 0
if sub in s:
count += 1
print count

if __name__ == '__main__':
import doctest
doctest.testmod()

Any help would be greatly appreciated.

Well on the forums remember to use code tags

[code]

code here

[/code]
But here is the code you have

``````def count(sub, s):
"""
>>> count('is', 'Mississippi')
3
>>> count('an', 'banana')
3
>>> count('ana', 'banana')
3
>>> count('nana', 'banana')
3
>>> count('nanan', 'banana')
3
"""
count = 0
if sub in s:
count += 1
print count

if __name__ == '__main__':
import doctest
doctest.testmod()``````

There are a few problem is see with your doc. Firstly this one:
>>> count('ana', 'banana')
2
there is only ONE ana in banana, the other one is a cross over of it, so in that case you should have
>>> count('ana', 'banana')
1

Also your function is wrong, it will only ever get one as a return value at max, that is because an if statement executes and then goes on.
This seems like a more relevant function.

``````def count(string, sub):
return string.count(sub)``````

See how that goes, and ill help out if there is something still wrong with it.

Just a note, since count() is a builtin Python function, avoid using it for your own function name. Use something like mycount().

Thank you all for your replies. It was greatly appreciated and helped me a lot.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.