Sign in to follow this  

find function (python string problem)

This topic is 4113 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I have here a function that origonally found the place where a character first appeared in a string beginning from the first character. My job was to modify it so the user can start the search at whichever index the user wished. My problem is that some starting numbers work properly, whilst others don't. I've looked over it a million times and I can't seem to figure it out. Here's the code:
def find(strng, ch, startat):
    index = startat
    while index < len(strng):
        if strng[startat:index] == ch:
            return index
        index = index + 1
    return -1

print find("banana", "a", 2)

This version will print out a -1 when it should print a 3.

Share this post


Link to post
Share on other sites
Python already have function you are writing (in string module):
import string
print string.find("banana", "a", 2)
or (as string member function)
print "banana".find("a", 2)

Question which you should ask to yourself is - do you know what strng[startat:index] is evaluating to? (if you don't print ou it in while loop iteration, just before if statement).

Share this post


Link to post
Share on other sites
Quote:
Original post by bubu LV
Python already have function you are writing (in string module):
import string
print string.find("banana", "a", 2)
or (as string member function)
print "banana".find("a", 2)


Aware, it's just for an exercise.

Quote:

This takes a slice (ie, substring) of strng. I'm pretty sure what you want is:


Works, thanks.

Share this post


Link to post
Share on other sites
Nevermind, how come this:
def find(strng, ch, startat):
index = startat
while index < len(strng):
if strng[index] == ch:
return index
index = index + 1
return -1

print find("vanilla", "a", 1)



Prints 1?

EDIT: pfft, nevermind. :p

Share this post


Link to post
Share on other sites

This topic is 4113 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this