0

I have an array and an input, if I input something I want to use .startswith() with my array, for example if I have this:

Array = ['foo','bar']

And if I input "fo" I want it to match it with "foo" and then return the index, in this case 0. How would I do this?

2
  • Do you mean a = ['foo', 'bar'] or is foo a variable there... Commented Mar 8, 2016 at 17:43
  • See stackoverflow.com/questions/2170900/… for how to find a substring. Then just change the substring match to startswith(). Commented Mar 8, 2016 at 17:44

3 Answers 3

2

MaryPython's answer is generally fine. Alternatively, in O(n) instead of O(n^2), you could use

for index, item in enumerate(my_list):
       if item.startswith('fo'):
            print(index)

I've used enumerate to walk the index with the item

Note that Marky's implementation fails on this array

 ['fo','fo','fobar','fobar','hi']

because .index always returns the first instance of a repeated occurrence (but otherwise his solution is fine and intuitive)

Sign up to request clarification or add additional context in comments.

Comments

1

Here is one solution. I iterated through the list and for each item checked if they start with the string 'fo' (or whatever your want to check with). If it starts with that string it prints the index of that item. I hope this helps!

Array = ['foo', 'bar']

for item in Array:
    if item.startswith('fo'):
        print(Array.index(item))

5 Comments

Thankyou, I had to make a few minor adjustments but it is working!
Glad I could help, if my answer worked be sure to check it as accepted. Thanks!
It was a typo, I fixed it.
Great, looks good. I would note that it doesn't work with repetitions, but that's probably fine as long as OP didn't specify he neesd them
I looked at your answer and it looks great. Gave it an upvote.
0
#!/usr/bin/python
# -*- coding: ascii -*-

Data = ['bleem', 'flargh', 'foo', 'bar' 'beep']

def array_startswith(search, array):
    """Search an iterable object in order to find the index of the first
    .startswith(search) match of the items."""
    for index, item in enumerate(array):
        if item.startswith(search):
            return(index)
    raise(KeyError)
    ## Give some sort of error. You probably want to raise an error rather
    ##     than returning None, as this might cause a logic error in the
    ##     later program. I think KeyError is correct, based on the question.
    ## See Effective Python by Brett Slatkin, Page 29...

if __name__ == '__main__':
    lookfor='fo'
    try:
        result=array_startswith(lookfor, Data)
    except KeyError as e:
        print("'{0}' not found in Data, Sorry...".format(lookfor))
    else:
        print("Index where '{0}' is found is: {1}. Found:{2}".format(lookfor, 
            result, Data[result]))
    finally:
        print("Try/Except/Else/Finally Cleanup happens here...")
    print("Program done.")

3 Comments

Wow, that seems like a lot more hassle than needed. Take a look at en_Knight's or my answer, much less code but still gets the job done.
I was going for a more "batteries included" answer, giving as complete an answer as I could.
According to "The Zen of Python" (type import this into the python shell to see), "Simple is better than complex.".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.