Python Practice › String Programs › Program 43
Position of a word in a sentence
Write a Python program to find the position (word number, starting at 1) of a word in a sentence.
Input
word = "problems", text = "I am solving problems based on strings"
Output
word number: 4 character index: 13
Approach
- Split into words and use
index(); add 1 for a human-friendly position.
Solution
text = "I am solving problems based on strings"word = "problems"words = text.split()print("word number:", words.index(word) + 1)print("character index:", text.find(word))Output
word number: 4 character index: 13
Line by line
Line 4
List indexes start at 0, so add 1.
Line 5
find() gives the character position instead.
Learn the concept
New to this topic? Read the lesson, then come back.