I'm writing a function where the user inputs a word, then inputs a string, and the function identifies all occurrences and the position of that word in a string (although it's actually converted to a list halfway through).
The code I have currently is only identifying the first occurrence of the word, and none further. It also doesn't identify the word if the word is the first word in the string, returning an empty list. It will also say the word's actual position - 1, as the first word is counted as zero.
I have attempted to curb this problem in two ways, the first of which doing a aString.insert(0, ' ')
, the second of which doing for i in __: if i == int: i += 1
. Neither of these work.
Also, when doing the .insert
, I tried putting a character in the space instead of, well, a space (as this part doesn't get printed anyway), but that didn't work.
Here is the code:
def wordlocator(word):
yourWord = word
print("You have chosen the following word: " +yourWord)
aString = input("What string would you like to search for the given word?")
aString = aString.lower()
aString = aString.split()
b = [(i, j) for i, j in enumerate(aString)]
c = [(i, x) for i, x in b if x == yourWord]
return c
The output I'm looking for is that if someone did...
wordlocator("word")
"please input a string generic message" "that is a word"
"4, word"
Currently that would work, but it'd print "3, word"
. If the string was "that is a word and this is also a word"
then it'd ignore the further occurrence of "word"
.
edit: Got it working now, used a simpler piece of code. Thanks for your help all!