[Tutor] why does this fail
Christian Witts
cwitts at compuscan.co.za
Wed Aug 25 12:27:39 CEST 2010
On 25/08/2010 12:00, Roelof Wobben wrote:
> Hello,
>
> I have this programm :
>
> def remove_letter(letter, strng):
> """
> >>> remove_letter('a', 'apple')
> 'pple'
> >>> remove_letter('a', 'banana')
> 'bnn'
> >>> remove_letter('z', 'banana')
> 'banana'
> >>> remove_letter('i', 'Mississippi')
> 'Msssspp'
> """
> antwoord=""
> for letter in strng:
> print letter, strng
> if letter in strng:
> print "false"
> else:
> print "true"
> return antwoord
>
> x=remove_letter('a', 'apple')
> print x
>
> But now everything is false even a in apple.
>
> What is here wrong ?
>
> Roelof
>
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
You're rebinding the variable `letter`.
It is an input variable for your function but then you use it as the
character store while iterating through your string variable `strng`.
What your control should look like would be more like
for character in strng:
if letter == character:
print 'false' # this should be true, it is a match just like in
your example
else:
print 'true'
I'm assuming this function is just for learning purposes because there's
a built-in string function you can use called replace and you'd use it
as such `'apple'.replace('a', '')`.
PS: Once you've gotten it to work convert it to a list comprehension,
they are incredibly useful and a great tool.
--
Kind Regards,
Christian Witts
More information about the Tutor
mailing list