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. 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(' ')

Sign up to request clarification or add additional context in comments.

2 Comments

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.
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.
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])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.