1

I'm trying to create a program that will take input of a sentence and a word and check that sentence for the word and return the index of the beginning of the word i.e.

sentence = "random set of words" 
     word = "of"
     result = 9

This is what I tried

sentence = (input("Enter a sentence: "))
word = (input("Enter a Word: "))

result = sentence.split()

for x in sentence:
  if x == (word):
    boom = enumerate(word)
print(boom)
1
  • It should be, for x in result: so that you can get individual words each time the loop runs.
    – pvkcse
    Commented Sep 12, 2017 at 1:43

2 Answers 2

2

Just use index()

a = "aa bb cc"

b = "bb"

print a.index(b)

If the OP wants it to only count letters:

a = "aa bb cc"

b = "bb"

index_t = a.index(b)

real_index = index_t - a[:index_t].count(' ')

2
  • This will also count the whitespaces as characters, so the original example returns 11, and I think the OP wants it to only count letters, so strip the whitespaces and this is best.
    – Sam51
    Commented Sep 12, 2017 at 1:47
  • Some error will happen if use strip, like string "go fire of yeah", it will be "gofireofyeah", the index of "of" will be 2 not 7.
    – Asen
    Commented Sep 12, 2017 at 2:06
1

Assuming the word only appears once, I'd do it like this:

sentence = sentence.split(word)
sentence[0] = sentence[0].replace(" ","")
result = len(sentence[0])

Not the answer you're looking for? Browse other questions tagged or ask your own question.