variables in string.count

Matteo Dell'Amico della at toglimi.linux.it
Fri Jun 4 03:01:25 EDT 2004


ntg85 wrote:
> Can you use variables in string.count or string.find? I tried, and
> IDLE gives me errors.
> Here's the code:
> while list:
>     print 
>     letter = raw_input("What letter? ")
>     string.lower(letter)
>     guess = string.count(letter, list)
>     if guess == -1:
>         print "Try again!"
>     else:
>         list.remove(letter)
> the error is:
> TypeError: expected a character buffer object
> Thanks.

You shouldn't use list as a variable name: it's already a builtin 
function, and it could create problems to you.

As your exception states, string.count needs a string to work on, and 
string.lower doesn't modify the object in place (strings are immutable), 
  but it would return a new object.

I'd code it like this:

while secret:
     print
     letter = raw_input("What letter? ").lower()
     # we probably should do something to make sure len(letter) == 1
     if letter not in secret:
         print "Try again!"
     else:
         secret = secret.replace(letter, '', 1)

-- 
Ciao,
Matteo



More information about the Python-list mailing list