0

I'm writing a program where the user has to enter a set of string characters. They then pick a keyword that may or may not be in the string. If it is then the program will run through the string and see how many times the keyword appear and it will print this to the screen. I have done this so it does it but if the keyword appears twice. How do I get it so if the word appears twice then the program will print all positions of it?

This is what i have so far:

#Start by making a string
String = input("Please enter a set of string characters.\n")

#Make the user choose a keyword
Keyword = input("Please enter a keyword that we can tell you the position of.\n")

#Split the string into single words assigning the position to the word after the space
IndivualWords = String.split(' ')

#Start an IF statement 
if Keyword in IndivualWords:

    #If the IF is true then access the index and assign the keyword a position 
    pos = IndivualWords.index(Keyword)

    #Print the position of the word
    print (pos +1)

else:

    #Print an error
    print("That word is not in the string.")
milos.ai
  • 3,882
  • 7
  • 31
  • 33
AxJ
  • 1
  • 2
  • 1
    Possible duplicate of [Basic indexing recurrences of a substring within a string (python)](http://stackoverflow.com/questions/6987702/basic-indexing-recurrences-of-a-substring-within-a-string-python) – FamousJameous Aug 30 '16 at 14:56
  • Duplicate of http://stackoverflow.com/questions/6294179/how-to-find-all-occurrences-of-an-element-in-a-list ? – Chris_Rands Aug 30 '16 at 14:57
  • This might help: https://stackoverflow.com/questions/3873361/finding-multiple-occurrences-of-a-string-within-a-string-in-python @Chris_Rands that question isn't really similar to this though – Dartmouth Aug 30 '16 at 14:57
  • You can use [count](http://stackoverflow.com/questions/2600191/how-can-i-count-the-occurrences-of-a-list-item-in-python) method for your list and a `foreach` loop. – gonczor Aug 30 '16 at 14:58

4 Answers4

4

using enumerate() in an example where "een" is the keyword, line the input :

keyword = "een"
line = "een aap op een fiets"
for index, word in enumerate(line.split()):
    if word == keyword:
        print(index)
Jacob Vlijm
  • 3,099
  • 1
  • 21
  • 37
  • Doesn't print the position but the word index. – vz0 Aug 30 '16 at 16:06
  • @vz0 Looking at the question, that's what OP is looking for. – Jacob Vlijm Aug 30 '16 at 16:07
  • He is printing the char index, not the word index. In your example you print 0, 3, and he wants to print 0, 11. – vz0 Aug 30 '16 at 16:09
  • 1
    @vz0 In the OP's code, `IndivualWords` is a _list_ of words, not a string. So, `IndivualWords.index(Keyword)` returns an index into a list of words, not an index into a string. – John1024 Aug 30 '16 at 16:21
1

You could use re.finditer, here's a little example out of your example:

import re

sentence = input("Enter a set of string characters:")
keyword = input("Enter a keyword that we can tell you the position of:")

for m in re.finditer(keyword, sentence):
    print('{0} found {1}-{2}'.format(keyword, m.start(), m.end()))
BPL
  • 9,632
  • 9
  • 59
  • 117
1

The index method, as you found, returns just the first match:

>>> words = 'This is the time that the clock strikes'.split()
>>> words.index('the')
2

This list comprehension will return the locations of all matches:

>>> [i for i, word in enumerate(words) if word == 'the']
[2, 5]

If you want the list computed for all the words and formatted:

>>> print('\n'.join('%-7s: %s' % (w, ' '.join(str(i) for i, word in enumerate(words) if word == w)) for w in words))
This   : 0
is     : 1
the    : 2 5
time   : 3
that   : 4
the    : 2 5
clock  : 6
strikes: 7
John1024
  • 109,961
  • 14
  • 137
  • 171
1

You can use the regex method finditer()

>>> keyword = 'fox'
>>> s = 'The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.'

>>> from re import finditer
>>> print [match.start(0) for match in finditer(keyword, s)]
[16, 61]

or if you need the ranges of the sub strings:

>>> print [(match.start(0), match.end(0)) for match in re.finditer(keyword, s)]
[(16, 19), (61, 64)]
ospahiu
  • 3,465
  • 2
  • 13
  • 24