By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
444,001 Members | 1,176 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 444,001 IT Pros & Developers. It's quick & easy.

[Array] Finding index that contains part of a string?

P: n/a
Hello

Out of curiosity, is there a better way in Python to iterate through
an array, and return the index of each item that contains the bit
somewhere in its value, ie. index() doesn't work because it only
returns if the value only contains the item I'm looking for.

This works:
========
next = re.compile(">&#9658<")
i = 0
for item in items:
m = next.search(item)
if m:
print "Found Next in item %s" % i
i = i + 1
========

Thank you.
Nov 12 '08 #1
Share this Question
Share on Google+
1 Reply


P: n/a
Out of curiosity, is there a better way in Python to iterate through
an array, and return the index of each item that contains the bit
somewhere in its value, ie. index() doesn't work because it only
returns if the value only contains the item I'm looking for.

This works:
========
next = re.compile(">&#9658<")
i = 0
for item in items:
m = next.search(item)
if m:
print "Found Next in item %s" % i
i = i + 1
It looks like you're hunting for a fixed string, so I'd use

">&#9658<" in item

instead of bothering with a regexp.

You could do something like

indicies = [i for (i, item)
in enumerate(items)
if ">&#9658<" in item
# if next.search(item)
]

Or, if you just want those those indicies to find the
corresponding items, you can skip the enumerate()

indicies = [item for item in items
if ">&#9658<" in item
# if next.search(item)
]

You can use the "enumerate()" wrapper to get the indicies in your
loop if you really have to process them as such

for i, item in enumerate(items):
# if next.search(item)
if ">&#9658<" in item:
print "Found next item at", i

which is a bit more pythonic than "i = 0 ... i += 1"

-tkc

Nov 12 '08 #2

This discussion thread is closed

Replies have been disabled for this discussion.