Extract all numbers from a string

Python Practice › String Programs › Program 16

Extract all numbers from a string

EasyString Programs · 16 of 106

Write a Python program to get all the numbers from a multi-line string.

Input
a paragraph containing 1112, 1773, 444, 5324 and 555
Output
[1112, 1773, 444, 5324, 555]

Approach

  1. Use re.findall(r"\d+", text) and convert each match to int.

Solution

Python
import re text = """Sinak's 1112 aim is to 1773 create a new generation of people whounderstand 444 that an organization's 5324 success or failure isbased on 555 leadership excellence and not managerial acumen"""numbers = [int(n) for n in re.findall(r"\d+", text)]print(numbers)
Output
[1112, 1773, 444, 5324, 555]

Line by line

Line 6

\d+ matches each run of digits; the list comprehension converts them to integers.

Note

The original sample output listed 5324 twice and missed 444; the real numbers in the text are shown here.

Learn the concept

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

More string programs

← All 106 String Programs

Reverse the order of words

Python Practice › String Programs › Program 15

Reverse the order of words

EasyString Programs · 15 of 106

Write a Python program to rearrange a sentence so its words appear in reverse order.

Input
"Cricket Plays Virat"
Output
Virat Plays Cricket

Approach

  1. Split, reverse the list, join.

Solution

Python
text = "Cricket Plays Virat"print(" ".join(text.split()[::-1]))
Output
Virat Plays Cricket

Learn the concept

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

More string programs

← All 106 String Programs

Vowel count of each word

Python Practice › String Programs › Program 13

Vowel count of each word

EasyString Programs · 13 of 106

Write a Python program to count the vowels in each word and show the result as a dictionary.

Input
"We are Learning Python Codding"
Output
{'We': 1, 'are': 2, 'Learning': 3, 'Python': 1, 'Codding': 2}

Approach

  1. A dict comprehension maps each word to its vowel count.

Solution

Python
text = "We are Learning Python Codding"counts = {w: sum(ch in "aeiouAEIOU" for ch in w) for w in text.split()}print(counts)
Output
{'We': 1, 'are': 2, 'Learning': 3, 'Python': 1, 'Codding': 2}

Line by line

Line 2

ch in "aeiouAEIOU" is True or False; sum() counts the Trues.

Learn the concept

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

More string programs

← All 106 String Programs

Swap first and last letters of each word

Python Practice › String Programs › Program 12

Swap first and last letters of each word

EasyString Programs · 12 of 106

Write a Python program to exchange the first and last characters of every word in a string.

Input
"Its Online Learning"
Output
stI enlinO gearninL

Approach

  1. Split, swap each word, join again.

Solution

Python
def swap(word):    return word if len(word) < 2 else word[-1] + word[1:-1] + word[0] text = "Its Online Learning"print(" ".join(swap(w) for w in text.split()))
Output
stI enlinO gearninL

Line by line

Line 2

One-letter words are returned unchanged.

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 characters

Python Practice › String Programs › Program 11

Swap the first and last characters

EasyString Programs · 11 of 106

Write a Python program to swap the first and last characters of a string.

Input
"SqaTool"
Output
lqaTooS

Approach

  1. Build last + middle + first.

Solution

Python
text = "SqaTool"swapped = text[-1] + text[1:-1] + text[0] if len(text) > 1 else textprint(swapped)
Output
lqaTooS

Line by line

Line 2

text[1:-1] is everything between the first and last characters.

Note

The original sample showed “IqaTooS” with a capital I, but swapping keeps the original letters, so the result is “lqaTooS”.

Learn the concept

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

More string programs

← All 106 String Programs

String length with a loop

String length with a loop

EasyString Programs · 9 of 106

Write a Python program to calculate the length of a string with a loop instead of len().

Input
"sqatools"
Output
8 True

Approach

  1. Count the characters one by one.

Solution

Python
text = "sqatools"count = 0for _ in text:    count += 1print(count, count == len(text))
Output
8 True

Learn the concept

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

More string programs

← All 106 String Programs

Longest and shortest word

Longest and shortest word

EasyString Programs · 7 of 106

Write a Python program to find the longest and the shortest word in a string.

Input
"Python makes string handling easy"
Output
Longest: handling
Shortest: easy

Approach

  1. Split into words and use max / min with key=len.

Solution

Python
text = "Python makes string handling easy"words = text.split()print("Longest:", max(words, key=len))print("Shortest:", min(words, key=len))
Output
Longest: handling
Shortest: easy

Line by line

Lines 3-4

key=len compares words by their length; on a tie, the first such word wins.

Learn the concept

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

More string programs

← All 106 String Programs

Vowel or consonant

Vowel or consonant

EasyString Programs · 6 of 106

Write a Python program to test whether a letter is a vowel or a consonant.

Input
"e", "K", "3"
Output
e -> vowel
K -> consonant
3 -> not a single letter

Approach

  1. Reject non-letters, then check membership in “aeiou”.

Solution

Python
def kind(ch):    if not ch.isalpha() or len(ch) != 1:        return "not a single letter"    return "vowel" if ch.lower() in "aeiou" else "consonant" for ch in ["e", "K", "3"]:    print(ch, "->", kind(ch))
Output
e -> vowel
K -> consonant
3 -> not a single letter

Line by line

Lines 2-3

Digits, symbols and longer strings are rejected first.

Learn the concept

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

More string programs

← All 106 String Programs

Count occurrences of a substring

Count occurrences of a substring

EasyString Programs · 5 of 106

Write a Python program to count how many times a substring occurs in a string.

Input
text = "the cat sat on the mat with the hat", sub = "the"
Output
3
4

Approach

  1. Use str.count().

Solution

Python
text = "the cat sat on the mat with the hat"print(text.count("the"))print(text.count("at"))
Output
3
4

Line by line

Line 2

count() counts non-overlapping occurrences.

Note

Because matches do not overlap, "aaaa".count("aa") is 2, not 3.

Learn the concept

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

More string programs

← All 106 String Programs

Reverse a string if its length is a multiple of 4

Reverse a string if its length is a multiple of 4

EasyString Programs · 4 of 106

Write a Python program to reverse a string if its length is a multiple of 4; otherwise return it unchanged.

Input
"Python", "sqatools"
Output
Python -> Python
sqatools -> slootaqs

Approach

  1. Check len(text) % 4 == 0, then reverse with [::-1].

Solution

Python
for text in ["Python", "sqatools"]:    result = text[::-1] if len(text) % 4 == 0 else text    print(text, "->", result)
Output
Python -> Python
sqatools -> slootaqs

Line by line

Line 2

“sqatools” has 8 characters, so it is reversed; “Python” has 6, so it is not.

Learn the concept

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

More string programs

← All 106 String Programs