1

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.

  • Does this answer your question? [How to find all occurrences of an element in a list?](https://stackoverflow.com/questions/6294179/how-to-find-all-occurrences-of-an-element-in-a-list) – Grady Clark Jan 13 '20 at 17:20

2 Answers2

4

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]
C.Nivs
  • 12,353
  • 2
  • 19
  • 44
tomgalpin
  • 1,943
  • 1
  • 4
  • 12
  • Thanks for the reply, but there seems to be a syntax error in the print statement. – soham_dhole Jan 13 '20 at 17:29
  • 1
    As you have tagged this with Python 3.x this is the syntax for that version of python .. For older versions use ```print [n for (n, e) in enumerate(text.split()) if e == 'abc'] ``` – tomgalpin Jan 13 '20 at 17:31
1
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)
arun n a
  • 684
  • 9
  • 26