Write a Python program to count how many times a whole word occurs in a string.
Input
"food" in "I want to eat fast food"; "are" in "We are learning Python, wow are you"
Output
1
2
Approach
Split into words, strip punctuation, count matches.
Solution
Python
defcount_word(text,word):returnsum(1forwintext.split()ifw.strip(",.!?")==word)print(count_word("I want to eat fast food","food"))print(count_word("We are learning Python, wow are you","are"))
Output
1
2
Line by line
Line 2
Counting whole words avoids matching “are” inside “hare”.
Learn the concept
New to this topic? Read the lesson, then come back.
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
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.
Write a Python program to convert number words into a number.
Input
"five four three two one"
Output
54321
Approach
Map each word to its digit and join.
Solution
Python
words=["zero","one","two","three","four","five","six","seven","eight","nine"]text="five four three two one"digits="".join(str(words.index(w))forwintext.split())print(int(digits))
Output
54321
Line by line
Line 4
words.index(w) is the digit for each word.
Learn the concept
New to this topic? Read the lesson, then come back.
Formatting rounds, so 2.14652 becomes “2.147”, not “2.146” as the original sample showed. Use str(int(x * 1000) / 1000) if you need to cut off digits instead.
Learn the concept
New to this topic? Read the lesson, then come back.