Consider,
text = 'lmn pqr xyz abc def pqr abc'
I need to get the indices of both the occurances of word abc
from the string str
.
I tried text.split().index('abc')
the output that I'm getting is 3
.
I need both 3
and 6
as output.
Consider,
text = 'lmn pqr xyz abc def pqr abc'
I need to get the indices of both the occurances of word abc
from the string str
.
I tried text.split().index('abc')
the output that I'm getting is 3
.
I need both 3
and 6
as output.
Dont assign to str
as it is a type.
This should do what you want
>>> text = 'lmn pqr xyz abc def pqr abc'
>>> print([n for (n, e) in enumerate(text.split()) if e == 'abc'])
[3, 6]
str = "lmn pqr xyz abc def pqr abc"
indices = [i for i, element in enumerate(str.split()) if element=="abc"]
print(indices)
Output
[3, 6]
First split the string and make it a list that is str.split()
then it becomes ['lmn', 'pqr', 'xyz', 'abc', 'def', 'pqr', 'abc']
. Then take each element and its index position of splited str, we use for loop and enumerate here. If any item matched "abc" then its index position is appended to the indices list.
If you want to know the total occurrence of "abc" in str then use len(indices)
For better understanding I am writing the above code without using list comprehension:
str = "lmn pqr xyz abc def pqr abc"
indices = []
for i, element in enumerate(str.split()):
if element=="abc":
indices.append(i)
print(f"The index position of 'abc' are {indices}")
Similarly, if you want to find the index position of all the items then try this:
str = "lmn pqr xyz abc def pqr abc"
deduped_str = set(str.split())
result = dict()
for item in deduped_str:
indices = [i for i, element in enumerate(str.split()) if element==item]
result[item] = indices
print(result)