Remove blank strings from a list

Python Practice › String Programs › Program 53

Remove blank strings from a list

EasyString Programs · 53 of 106

Write a Python program to remove blank strings from a list of strings.

Input
["Python", " ", " ", "sqatools"]
Output
['Python', 'sqatools']

Approach

  1. Keep items whose stripped text is not empty.

Solution

Python
items = ["Python", " ", " ", "sqatools"]print([s for s in items if s.strip()])
Output
['Python', 'sqatools']

Line by line

Line 2

" ".strip() is "", which is falsy, so blank items are dropped.

Learn the concept

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

More string programs

← All 106 String Programs

Replace several characters at once

Python Practice › String Programs › Program 52

Replace several characters at once

EasyString Programs · 52 of 106

Write a Python program to replace a with 1, t with 2 and o with 3 in one step.

Input
"Sqatool python"
Output
Sq1233l py2h3n

Approach

  1. Build a translation table with str.maketrans and apply translate.

Solution

Python
text = "Sqatool python"table = str.maketrans({"a": "1", "t": "2", "o": "3"})print(text.translate(table))
Output
Sq1233l py2h3n

Line by line

Line 2

maketrans maps each character to its replacement.

Line 3

translate replaces all of them in a single pass.

Learn the concept

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

More string programs

← All 106 String Programs

Replace several words at once

Python Practice › String Programs › Program 51

Replace several words at once

EasyString Programs · 51 of 106

Write a Python program to replace several words using a dictionary of replacements.

Input
"I'm learning python at Sqatools"; python → SQA, sqatools → TOOLS
Output
I'm learning SQA at TOOLS

Approach

  1. Use a regex that matches any of the words, ignoring case, and look up each replacement.

Solution

Python
import re text = "I'm learning python at Sqatools"replacements = {"python": "SQA", "sqatools": "TOOLS"}pattern = r"\b(" + "|".join(replacements) + r")\b"print(re.sub(pattern, lambda m: replacements[m.group(0).lower()], text, flags=re.IGNORECASE))
Output
I'm learning SQA at TOOLS

Line by line

Line 5

Builds the pattern \b(python|sqatools)\b.

Line 6

For every match the lambda returns the replacement, looked up in lower case.

Learn the concept

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

More string programs

← All 106 String Programs

Split a string on vowels

Python Practice › String Programs › Program 50

Split a string on vowels

EasyString Programs · 50 of 106

Write a Python program to split a string wherever a vowel appears.

Input
"qwerty"
Output
['qw', 'rty']
pr gr mm ng

Approach

  1. re.split("[aeiou]", text) removes the vowels and splits there.

Solution

Python
import reprint(re.split(r"[aeiouAEIOU]", "qwerty"))print(" ".join(re.split(r"[aeiou]", "programming")))
Output
['qw', 'rty']
pr gr mm ng

Learn the concept

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

More string programs

← All 106 String Programs

Mirror image of a string

Python Practice › String Programs › Program 49

Mirror image of a string

EasyString Programs · 49 of 106

Write a Python program to print the mirror image (reverse) of a string.

Input
"Python"
Output
nohtyP

Approach

  1. [::-1].

Solution

Python
print("Python"[::-1])
Output
nohtyP

Learn the concept

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

More string programs

← All 106 String Programs

First 2 and last 2 characters

Python Practice › String Programs › Program 48

First 2 and last 2 characters

EasyString Programs · 48 of 106

Write a Python program to build a string from the first 2 and last 2 characters.

Input
"Sqatools"
Output
Sqls

Approach

  1. Join [:2] and [-2:].

Solution

Python
text = "Sqatools"print(text[:2] + text[-2:])
Output
Sqls

Learn the concept

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

More string programs

← All 106 String Programs

First 4 characters

Python Practice › String Programs › Program 47

First 4 characters

EasyString Programs · 47 of 106

Write a Python program to get the first 4 characters of a string.

Input
"Sqatools"
Output
Sqat

Approach

  1. Slice [:4].

Solution

Python
print("Sqatools"[:4])
Output
Sqat

Learn the concept

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

More string programs

← All 106 String Programs

Words longer than n characters

Python Practice › String Programs › Program 46

Words longer than n characters

EasyString Programs · 46 of 106

Write a Python program to find the words longer than a given length.

Input
length = 3, text = "We are learning python"
Output
learning python

Approach

  1. Filter words by len(w) > n.

Solution

Python
n = 3text = "We are learning python"print(" ".join(w for w in text.split() if len(w) > n))
Output
learning python

Learn the concept

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

More string programs

← All 106 String Programs

Repeat vowels 3 times and consonants 2 times

Python Practice › String Programs › Program 14

Repeat vowels 3 times and consonants 2 times

MediumString Programs · 14 of 106

Write a Python program that repeats each vowel 3 times and each consonant 2 times, leaving spaces alone.

Input
"Sqa Tools Learning"
Output
SSqqaaa TToooooollss LLeeeaaarrnniiinngg

Approach

  1. Choose the repeat count for each character and join the pieces.

Solution

Python
text = "Sqa Tools Learning"out = []for ch in text:    if ch.lower() in "aeiou":        out.append(ch * 3)    elif ch.isalpha():        out.append(ch * 2)    else:        out.append(ch)print("".join(out))
Output
SSqqaaa TToooooollss LLeeeaaarrnniiinngg

Line by line

Line 9

Building a list and joining once is faster than adding to a string in a loop.

Learn the concept

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

More string programs

← All 106 String Programs

Replace the second occurrence of each character

Python Practice › String Programs › Program 10

Replace the second occurrence of each character

MediumString Programs · 10 of 106

Write a Python program to replace the second occurrence of every character with “$”.

Input
"Programming"
Output
Prog$am$in$

Approach

  1. Count characters as you go; when a count reaches 2, write “$” instead.

Solution

Python
text = "Programming"seen = {}result = ""for ch in text:    seen[ch] = seen.get(ch, 0) + 1    result += "$" if seen[ch] == 2 else chprint(result)
Output
Prog$am$in$

Line by line

Line 5

Count each character as it appears.

Line 6

Only the exact second occurrence becomes “$”; the third “m” or “g” would stay.

Learn the concept

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

More string programs

← All 106 String Programs