Python String Programs with Solutions

Python Practice › String Programs

Python String Programs with Solutions

106 programs101 easy5 medium0 hard

106 string programs that cover slicing, searching, counting, replacing, splitting and joining text. They are among the most common Python interview questions, and each one has an explained solution with real output.

Before you start

Read the Strings & Methods and String Formatting & f-strings lesson first if the topic is new to you.

All programs

Build a string character by character

Python Practice › Loop Programs › Program 3

Build a string character by character

EasyLoop Programs · 3 of 90

Write a Python program that adds each character of a word from the user to an empty string.

Input
python
Output
Enter a word: python
python

Approach

  1. Start with an empty string and append each character with +=.

Solution

Python
word = input("Enter a word: ")result = ""for ch in word:    result += chprint(result)
Outputtyped input: python
Enter a word: python
python

Line by line

Line 2

The empty string is the starting value.

Lines 3-4

Each loop pass appends one character.

Learn the concept

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

More loop programs

← All 90 Loop Programs

Extract 10-digit mobile numbers

Python Practice › String Programs › Program 106

Extract 10-digit mobile numbers

EasyString Programs · 106 of 106

Write a Python program to get all 10-digit mobile numbers from a string.

Input
a paragraph containing short numbers and four 10-digit numbers
Output
['8988858683', '2312245566', '4532892234', '9999234355']

Approach

  1. Match exactly 10 digits with word boundaries.

Solution

Python
import re text = """We have 2233 some employee8988858683whos 3455 mobile numbers are randomly distributed2312245566we want 453452 to get4532892234all the mobile numbers9999234355from this given string."""print(re.findall(r"\b\d{10}\b", text))
Output
['8988858683', '2312245566', '4532892234', '9999234355']

Line by line

Line 11

\b stops a match inside a longer number, and {10} requires exactly ten digits.

Learn the concept

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

More string programs

← All 106 String Programs

Extract email addresses

Python Practice › String Programs › Program 105

Extract email addresses

EasyString Programs · 105 of 106

Write a Python program to extract all email addresses from a string.

Input
a paragraph with four email addresses
Output
['john@gmail.com', 'jay@lic.com', 'hari@facebook.com', 'mery@hotmail.com']

Approach

  1. A regex for “letters @ domain . extension”.

Solution

Python
import re text = """We have some employee whosjohn@gmail.comemail id's are randomly distributedjay@lic.comwe want to gethari@facebook.comall the emailmery@hotmail.comid's from this given string."""print(re.findall(r"[\w.+-]+@[\w-]+\.[\w.]+", text))
Output
['john@gmail.com', 'jay@lic.com', 'hari@facebook.com', 'mery@hotmail.com']

Line by line

Line 11

The pattern matches the name, “@”, a domain and at least one dot-separated extension.

Learn the concept

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

More string programs

← All 106 String Programs

Each character on a new line

Python Practice › String Programs › Program 104

Each character on a new line

EasyString Programs · 104 of 106

Write a Python program to print each character on its own line.

Input
"python"
Output
p
y
t
h
o
n

Approach

  1. Loop or print(*text, sep="\n").

Solution

Python
print(*"python", sep="\n")
Output
p
y
t
h
o
n

Line by line

Line 1

* unpacks the string into separate characters and sep="\n" puts each on its own line.

Learn the concept

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

More string programs

← All 106 String Programs

Print a string 3 times

Python Practice › String Programs › Program 103

Print a string 3 times

EasyString Programs · 103 of 106

Write a Python program to print a string 3 times.

Input
"sqatools"
Output
sqatoolssqatoolssqatools

Approach

  1. * 3.

Solution

Python
print("sqatools" * 3)
Output
sqatoolssqatoolssqatools

Learn the concept

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

More string programs

← All 106 String Programs

Collapse repeated characters

Python Practice › String Programs › Program 102

Collapse repeated characters

EasyString Programs · 102 of 106

Write a Python program to replace each group of repeated characters with a single character.

Input
"aabbccdd"
Output
abcd

Approach

  1. dict.fromkeys keeps one of each in order.

Solution

Python
print("".join(dict.fromkeys("aabbccdd")))
Output
abcd
Note

The result keeps the original order, “abcd”. The original sample’s “cabd” came from using a set, whose order is not defined.

Learn the concept

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

More string programs

← All 106 String Programs

Swap case

Python Practice › String Programs › Program 101

Swap case

EasyString Programs · 101 of 106

Write a Python program to swap upper and lower case.

Input
"Learning Python"
Output
lEARNING pYTHON

Approach

  1. swapcase().

Solution

Python
print("Learning Python".swapcase())
Output
lEARNING pYTHON

Learn the concept

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

More string programs

← All 106 String Programs

First repeated character and its index

Python Practice › String Programs › Program 100

First repeated character and its index

EasyString Programs · 100 of 106

Write a Python program to find the first character that repeats and the index of its first occurrence.

Input
"sqatools"
Output
('o', 4)

Approach

  1. Remember the first index of each character; stop at the first repeat.

Solution

Python
text = "sqatools"first_seen = {}for i, ch in enumerate(text):    if ch in first_seen:        print((ch, first_seen[ch]))        break    first_seen[ch] = i
Output
('o', 4)

Line by line

Lines 4-6

The first character seen twice is reported with the index where it first appeared.

Note

The loop finds the repeat at the second “o”, so the answer is (“o”, 4): “o” repeats before “s” does.

Learn the concept

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

More string programs

← All 106 String Programs

Index of each character

Python Practice › String Programs › Program 99

Index of each character

EasyString Programs · 99 of 106

Write a Python program to print the index of each character in a string.

Input
"sqatools"
Output
Index of s is 0
Index of q is 1
Index of a is 2
Index of t is 3
Index of o is 4
Index of o is 5
Index of l is 6
Index of s is 7

Approach

  1. enumerate() gives index and character.

Solution

Python
for i, ch in enumerate("sqatools"):    print(f"Index of {ch} is {i}")
Output
Index of s is 0
Index of q is 1
Index of a is 2
Index of t is 3
Index of o is 4
Index of o is 5
Index of l is 6
Index of s is 7

Learn the concept

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

More string programs

← All 106 String Programs