I have a list text_lines = ['asdf','kibje','ABC','beea']
and I need to find an index where string ABC
appears.
ABC = [s for s in text_lines if "ABC" in s]
ABC
is now "ABC".
How to get index?
I have a list text_lines = ['asdf','kibje','ABC','beea']
and I need to find an index where string ABC
appears.
ABC = [s for s in text_lines if "ABC" in s]
ABC
is now "ABC".
How to get index?
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]
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"]
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
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.