Syed Ali Zain Naqvi
Syed Ali Zain Naqvi

Reputation: 13

Finding nth position of substring in a string using python

Let's take example string, 'I am programmer and I am doing coding. I am interested in it' and the target word (substring) is 'am'. I want to find nth value of it where it is located by the complete words, not indexes. For example, substring 'am' is located on 2nd, 6th and 10 position. I tried searching but all the results were relevant to finding indexes. One I found about nth value didn't work for me. Code was giving error on ':' of 'IF'.

    parts= haystack.split(needle, n+1)
    if len(parts)<=n+1:
        return -1
    return len(haystack)-len(parts[-1])-len(needle)

Do you have an optimum and simple solution for this. I am trying to just solve the problem with possible solutions and logics. Your cooperation will be well appreciated.

Upvotes: 0

Views: 742

Answers (2)

Syed Ali Zain Naqvi
Syed Ali Zain Naqvi

Reputation: 13

I tried following code and it worked on the string below where the function is called.

    counter=0
    lst=[]
    if target in string:
        li=list(string.split(" ")) #li is list, string to list
        j = [i for i, x in enumerate(li) if x == "exam"]
        print("Positions of string ",target," is :-")
        for s in range(len(j)):
            print(j[s]+1)


    else:
        return "Target word not in the string."

print(findTargetWord("Today is my exam and exam is easy", "exam")) #it worked on this string 

I tried string Today is my sessional exam. I am not fully prepared for exam. I don't know, how I will perform in exam. Instead of returning me the correct answer, it print 21.

Upvotes: 0

Buddy Bob
Buddy Bob

Reputation: 5889

You can do something like this.

string = 'I am programmer and I am doing coding. I am interested in it'.split()
target = 'am'
for count,words in enumerate(string):
    if words == target:
        print(count)

This will give you 1,5,9. This is because indexes start from zero. Now ofcourse if you want 2,6,10 you can just add one to count whenever it is printed.

list comprehension

string = 'I am programmer and I am doing coding. I am interested in it'.split()
target = 'am'
wordPlace = [count for count,words in enumerate(string) if words == target]

Upvotes: 1

Related Questions