Python Practice › String Programs › Program 43

Position of a word in a sentence

EasyString Programs · 43 of 106

Write a Python program to find the position (word number, starting at 1) of a word in a sentence.

Advertisement
Input
word = "problems", text = "I am solving problems based on strings"
Output
word number: 4
character index: 13

Approach

  1. Split into words and use index(); add 1 for a human-friendly position.

Solution

Python
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.

More string programs

← All 106 String Programs

Leave a Comment