[Tutor] strings

Daniel Ehrenberg littledanehren at yahoo.com
Tue Dec 9 20:33:01 EST 2003


trypticon-at-SAFe-mail.net wrote:
> Hi,
>      i'm having a little trouble with this exercise
> problem. We're supposed to create a function called
> findchr(string,char) which will look for character
> char in string and return the index of the first
> occurrence of char, or -1 if char is not part of
> string. you can't use string.*find() or
> string.*index() functions or methods. The part where
> i'm having trouble is returning the index of the
> first occurrence of char. Any help would be
> appreciated. Thanks

As just about everyone else on this list said, this is
probably a homework assignment, so I won't give you
the answer. I'll only give you a hint. Try using list
comprehensions. These are fairly advanced, so I'll
walk you through how to use them.

>>> this_list = [5, 3, 6, 2, 5] #should be obvious
>>> [x for x in this_list] #goes through each item of
#this_list, calling it x, then returns x into a new
list
[5, 3, 6, 2, 5]
>>> [x**2 for x in this_list] #gets x squared for each
x in this_list
[25, 9, 36, 4, 25]
>>> [x for x in this_list if x!=5] #takes each x for
each x in this_list, but only if it doesn't equal 5
[3, 6, 2]
>>> [x for x in 'hello' if x!='l'] #strings can be
treated as lists, but it still returns a list
['h', 'e', 'o']
>>> enumerate(this_list) #makes an enumerator iterator
<enumerate object at 0x01651580>
>>> [(index, object) for index, object in
enumerate(this_list)] #each thing in enumerate(x) is a
tuple of the index and the thing in the list
[(0, 5), (1, 3), (2, 6), (3, 2), (4, 5)]
>>> [index for index, object in enumerate(this_list)
if object==5] #I don't want to give it away
[0, 4]

If you followed all of that, you can use similar
techniques to solve your problem.

Daniel Ehrenberg


__________________________________
Do you Yahoo!?
New Yahoo! Photos - easier uploading and sharing.
http://photos.yahoo.com/



More information about the Tutor mailing list