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

Longest run of a repeated character

Longest run of a repeated character

MediumString Programs · 8 of 106

Write a Python program to find the character that repeats most times in a row (consecutively) in a string.

Input
"aabbbbcccdd"
Output
b 4

Approach

  1. Walk through the string, counting the current run, and remember the longest one.

Solution

Python
text = "aabbbbcccdd"best_char, best_len = text[0], 1run_len = 1for i in range(1, len(text)):    if text[i] == text[i - 1]:        run_len += 1    else:        run_len = 1    if run_len > best_len:        best_char, best_len = text[i], run_lenprint(best_char, best_len)
Output
b 4

Line by line

Lines 5-8

The run grows while characters repeat and resets on a change.

Lines 9-10

Save the run if it is the longest so far.

Tip

itertools.groupby(text) groups consecutive equal characters for you.

Learn the concept

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

More string programs

← All 106 String Programs

Least frequent character

Python Practice › String Programs › Program 45

Least frequent character

EasyString Programs · 45 of 106

Write a Python program to find the least frequent character in a string.

Input
"abcdabdggfhf"
Output
c Counter({'a': 2, 'b': 2, 'd': 2, 'g': 2, 'f': 2, 'c': 1, 'h': 1})

Approach

  1. Count characters and take the one with the smallest count.

Solution

Python
from collections import Counter text = "abcdabdggfhf"counts = Counter(text)print(min(counts, key=counts.get), counts)
Output
c Counter({'a': 2, 'b': 2, 'd': 2, 'g': 2, 'f': 2, 'c': 1, 'h': 1})

Line by line

Line 5

key=counts.get compares characters by their counts; with ties, the first seen wins.

Learn the concept

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

More string programs

← All 106 String Programs