Jump to content


Python Help!


2 replies to this topic

#1 jpd750

    Young Padawan

  • Members
  • Pip
  • 11 posts

Posted 18 October 2009 - 07:12 PM

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

#2 ShadowMage

    Young Padawan

  • Members
  • Pip
  • 2 posts
  • Gender:Male
  • Location:Pennsylvania, USA

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.
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 fedekun

    Young Padawan

  • Members
  • Pip
  • 1 posts

Posted 21 December 2009 - 12:50 AM

I think you will be able to understand this

>>> 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