[Tutor] Strings
Alan Gauld
alan.gauld at btinternet.com
Wed Nov 5 18:51:45 CET 2014
On 05/11/14 13:19, William Becerra wrote:
> names = "John, Cindy, Peter"
> def find(str, ch, s):
> index = 0
> while index < len(str):
> if s==1:
> for char in names[:4]:
> if str[index] == ch:
> return index + 1
> index = index + 1
> if s==2:
> for char in names[6:11]:
> if str[index] == ch:
> return index + 1
> index = index + 1
> if s==3:
> for char in names[13:]:
> if str[index] == ch:
> return index + 1
> index = index + 1
> return -1
> print find(names,"n", 2)
>
> I intend for the parameter s to tell the interpreter which name to look at
> so that i get the index return value related to that name.
> Can Someone Please tell me why my code isn't working like I intend it to?
Note that you have a for loop over the characters in the name you are
interested in but you never use those characters you always use
str[index] which refers to the outer combined string.
Your logic is faulty, you don;t want to loop over every character in
str, you only want to loop over the characters in the name that you select.
You should look at the methods available on strings ( try
help(str) ) There are at least two that would simplify your
code: split() and find(). Unless you are deliberately
looking at the character comparison technique, in which
case split() would still be helpful.
HTH
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list