Search code examples
pythonstringpython-3.xpositionsubstring

Find position of word/substring in string (python 3.4.3)


I want to find the position of the WHOLE word in the string, but my code displays the position of the first character of the word.

string = input("Please input a sentence: ")
word = input("Please input a word: ")
string.lower()
word.lower()
list1 = string.split(' ')
position = string.index(word)
print (position)

Solution

  • Since you are asking the word as an input, you have the word size and you know the starting index, you could do: starting index + size.

    string = input("Please input a sentence: ")
    word = input("Please input a word: ")
    string.lower()
    word.lower()
    list1 = string.split(' ')
    position = string.index(word)
    print (position) // starting position
    print (position + len(word) ) // end position