Count occurrences of a word

Python Practice › String Programs › Program 44

Count occurrences of a word

EasyString Programs · 44 of 106

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

  1. Split into words, strip punctuation, count matches.

Solution

Python
def count_word(text, word):    return sum(1 for w in text.split() if w.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.

More string programs

← All 106 String Programs

Position of a word in a sentence

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.

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

Number words to digits

Python Practice › String Programs › Program 42

Number words to digits

EasyString Programs · 42 of 106

Write a Python program to convert number words into a number.

Input
"five four three two one"
Output
54321

Approach

  1. 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)) for w in text.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.

More string programs

← All 106 String Programs

Float to 3 decimal places as a string

Python Practice › String Programs › Program 41

Float to 3 decimal places as a string

EasyString Programs · 41 of 106

Write a Python program to format a float to 3 decimal places and convert it to a string.

Input
2.14652
Output
2.147 str

Approach

  1. Use the format spec .3f.

Solution

Python
x = 2.14652text = f"{x:.3f}"print(text, type(text).__name__)
Output
2.147 str
Note

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.

More string programs

← All 106 String Programs

Split and join a string

Python Practice › String Programs › Program 40

Split and join a string

EasyString Programs · 40 of 106

Write a Python program to split a string into words and join them with “-“.

Input
"Hello world"
Output
['Hello', 'world']
Hello-world

Approach

  1. split() then "-".join().

Solution

Python
parts = "Hello world".split()print(parts)print("-".join(parts))
Output
['Hello', 'world']
Hello-world

Learn the concept

New to this topic? Read the lesson, then come back.

More string programs

← All 106 String Programs

Remove newlines from a string

Python Practice › String Programs › Program 39

Remove newlines from a string

EasyString Programs · 39 of 106

Write a Python program to remove newline characters from a string.

Input
"objectoriented\nprogramming\n"
Output
'objectoriented\nprogramming'
'objectorientedprogramming'

Approach

  1. strip() for the ends, replace("\n", "") for everywhere.

Solution

Python
text = "objectoriented\nprogramming\n"print(repr(text.rstrip("\n")))print(repr(text.replace("\n", "")))
Output
'objectoriented\nprogramming'
'objectorientedprogramming'

Line by line

Line 2

rstrip("\n") removes only trailing newlines.

Line 3

replace removes them everywhere.

Learn the concept

New to this topic? Read the lesson, then come back.

More string programs

← All 106 String Programs

Convert to uppercase

Python Practice › String Programs › Program 38

Convert to uppercase

EasyString Programs · 38 of 106

Write a Python program to convert all the characters in a string to uppercase.

Input
"I live in pune"
Output
I LIVE IN PUNE

Approach

  1. Use upper().

Solution

Python
print("I live in pune".upper())
Output
I LIVE IN PUNE

Learn the concept

New to this topic? Read the lesson, then come back.

More string programs

← All 106 String Programs

Swap the first and last letters of a string

Python Practice › String Programs › Program 37

Swap the first and last letters of a string

EasyString Programs · 37 of 106

Write a Python program to exchange the first and last letters of a string.

Input
"We are learning python"
Output
ne are learning pythoW

Approach

  1. last + middle + first.

Solution

Python
text = "We are learning python"print(text[-1] + text[1:-1] + text[0])
Output
ne are learning pythoW

Learn the concept

New to this topic? Read the lesson, then come back.

More string programs

← All 106 String Programs

Does a string have special characters?

Python Practice › String Programs › Program 36

Does a string have special characters?

EasyString Programs · 36 of 106

Write a Python program to check whether a string contains special characters.

Input
"python$$#sqatools", "python"
Output
python$$#sqatools -> has special characters ['$', '$', '#']
python -> no special characters []

Approach

  1. A special character is not alphanumeric and not a space.

Solution

Python
for text in ["python$$#sqatools", "python"]:    special = [ch for ch in text if not ch.isalnum() and not ch.isspace()]    print(text, "->", "has special characters" if special else "no special characters", special)
Output
python$$#sqatools -> has special characters ['$', '$', '#']
python -> no special characters []

Learn the concept

New to this topic? Read the lesson, then come back.

More string programs

← All 106 String Programs

Remove duplicate characters

Python Practice › String Programs › Program 35

Remove duplicate characters

EasyString Programs · 35 of 106

Write a Python program to remove duplicate characters, keeping the first occurrence of each.

Input
"sqatools"
Output
sqatol

Approach

  1. dict.fromkeys keeps the first occurrence in order.

Solution

Python
text = "sqatools"print("".join(dict.fromkeys(text)))
Output
sqatol

Line by line

Line 2

Dictionary keys are unique and keep insertion order, so joining them gives the de-duplicated string.

Learn the concept

New to this topic? Read the lesson, then come back.

More string programs

← All 106 String Programs