Keep in mind, I am VERY new to python. Im trying to do this:
There is a string method called 'count'. Write an invocation that counts the number of 'a's in banana.
How do I do the above syntactically in python.
Thanks
Python Help!
Started by jpd750, Oct 18 2009 07:12 PM
2 replies to this topic
#1
Posted 18 October 2009 - 07:12 PM
#2
Posted 19 October 2009 - 08:30 AM
Heres how you would do it. You would want to use the list function to make the letters list, then you could count.
To count how many there are now, you could do:
and that should output 3.
Hope this helps.
wordlist = list("banana")
That will assign the variable wordlist to be an array, and that array will have all the letters in banana.To count how many there are now, you could do:
print wordlist.count("a")
and that should output 3.
Hope this helps.
#3
Posted 21 December 2009 - 12:50 AM
I think you will be able to understand this
But you can also do this
So you could rewrite it as
>>> def count(str, letter):
c = 0
for word in str:
if word == letter:
c += 1
return c
>>> count("banana", "a")
But you can also do this
>>> "banana".count("a")
So you could rewrite it as
>>> def count(str, letter):
return str.count(letter)
>>> count("banana", "a")
Edited by fedekun, 21 December 2009 - 12:52 AM.
1 user(s) are reading this topic
0 members, 1 guests, 0 anonymous users
