-1

I have a list text_lines = ['asdf','kibje','ABC','beea'] and I need to find an index where string ABCappears.

ABC = [s for s in text_lines if "ABC" in s]

ABC is now "ABC".
How to get index?

Danijel
  • 8,198
  • 18
  • 69
  • 133
  • possible duplicate of [Finding the index of an item given a list containing it in Python](http://stackoverflow.com/questions/176918/finding-the-index-of-an-item-given-a-list-containing-it-in-python) – Wim Ombelets Jul 24 '14 at 13:55
  • nah, not a duplicate of that – wim Jul 24 '14 at 13:55

4 Answers4

4

Greedy (raises exception if not found):

index = next(i for i, s in enumerate(text_lines) if "ABC" in s)

Or, collect all of them:

indices = [i for i, s in enumerate(text_lines) if "ABC" in s]
wim
  • 338,267
  • 99
  • 616
  • 750
0

Did you mean the index of "ABC" ?

If there is just one "ABC", you can use built-in index() method of list:

text_lines.index("ABC")

Else, if there are more than one "ABC"s, you can use enumerate over the list:

indices = [idx for idx,val in enumerate(text_lines) if val == "ABC"]
myildirim
  • 2,248
  • 2
  • 19
  • 25
0
text_lines = ['asdf','kibje','ABC','beea']

abc_index = text_lines.index('ABC')

if 'ABC' appears only once. the above code works, because index gives the index of first occurrence.

for multiple occurrences you can check wim's answer

shshank
  • 2,571
  • 1
  • 18
  • 27
  • Thanks. I need to detect not identical strings, but substrings too, like `xABCyz`. Do you have solution for that? – Danijel Jul 24 '14 at 14:22
0

Simple python list function.

index = text_lines.index("ABC")

If the string is more complicated, you may need to combine with regex, but for a perfect match this simple solution is best.

Andrew M
  • 61
  • 5