[Tutor] inputting strings into functions

Sean 'Shaleh' Perry shaleh@valinux.com
Wed, 14 Mar 2001 22:16:36 -0800


On Thu, Mar 15, 2001 at 03:48:35PM +1000, Paul Jones wrote:
> Hi-back again- I'm trying with little success to figure out how to input strings as parameters into a function definition. The problem is as follows.
> I have been given the following algorithm {in brackets} 
> {The following program counts the number of times the letter 'a' appears in a string:
> 
>   fruit = "banana" 
>   count = 0 
>   index = 0 
>   for char in fruit: 
>     if char == 'a': 
>       count = count + 1 
>   print count           }
>

fruit is a variable holding a string.  When you access it, you do not need
quotes.  When you quote something you turn it into a string.
So, foo is a variable, 'foo' is a string literal.

> 
> def countletters(string,letter):
>  fruit = 'string'
>  count=0
>  index=0
>  for char in fruit:
>   if char == 'letter':
>    count=count+1
>  print count
>

just remove the quotes when you use the variable.  Note the example code you
showed in the beginning did not quote fruit. 

For further help here, look at the string.py module shipped with python:

# convert UPPER CASE letters to lower case
def lower(s):
        """lower(s) -> string

        Return a copy of the string s converted to lowercase.

        """
        res = ''
        for c in s:
                res = res + _lower[ord(c)]
        return res