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

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