Reputation: 485
value = ["python:guru-age20",
"is_it_possible_time100:goodTime99",
"hmm_hope_no_onecanansswer"]
How to get a particular string from this list of strings? I need to find goodTime99
from the li[1]
string and its exact postion
if value.find("goodTime99") != -1:
I know will work if I give the entire string is_it_possible_time100:goodTime99
.
Otherwise how to exact the position by searching goodTime99
instead of searching for is_it_possible_time100:goodTime99
? value.index("goodTime99")
is giving an error.
I am not looking for whole string to search, value.index("is_it_possible_time100:goodTime99")
is fine but I don't want this. Anyway to do this?
Upvotes: 2
Views: 205
Reputation: 14854
if you want a single line answer you can have
In [339]: [value.index(x) for x in value if x.find("goodTime99") > -1]
Out[339]: [1]
simplest way could be :
it will give you all the index's of the strings containing your substring from the list
In [334]: value = ["python:guru-age20",
.....: "is_it_possible_time100:goodTime99",
.....: "hmm_hope_no_onecanansswer"]
In [335]: indexs = []
In [336]: for x in value:
.....: if x.find("goodTime99") > -1:
.....: indexs.append(value.index(x))
.....:
In [337]: print indexs
[1]
In [338]: int(*indexs)
Out[338]: 1
Upvotes: 2
Reputation: 1518
this will give you all the matches with also the indexes if you need:
filter(lambda x: x[1].find("goodTime99") != -1, enumerate(value))
if you want the indexes only, then
[e[0] for e in filter(lambda x: x[1].find("goodTime99") != -1, enumerate(value))]
for example, this is what I got:
>>> value = ["python:guru-age20", "is_it_possible_time100:goodTime99","hmm_hope_no_onecanansswer"]
>>> res = [e[0] for e in filter(lambda x: x[1].find("goodTime99") != -1, enumerate(value))]
>>> res
[1]
Upvotes: 1
Reputation: 55946
If you only want to check for the presence of "goodTime99"
in any string in the list, you could try:
value = ["python:guru-age20", "is_it_possible_time100:goodTime99","hmm_hope_no_onecanansswer"]
if any("goodTime99" in s for s in value):
# found it
If you need the exact position:
>>> next((i for i, s in enumerate(value) if "goodTime991" in s), -1)
1
or:
def find_first_substring(lst, substring):
return next((i for i, s in enumerate(lst) if substring in s), -1)
>>> find_first_substring(value, "goodTime99")
1
Upvotes: 2
Reputation: 399703
You simply need to search through each individual string in turn:
for s in value:
if s.find("goodTime99"):
print "found in", s
break
Upvotes: 0