Extract numbers as integers

Python Practice › String Programs › Program 83

Extract numbers as integers

EasyString Programs · 83 of 106

Write a Python program to extract the numbers from a string.

Input
"python 456 self learning 89"
Output
[456, 89]

Approach

  1. Keep words that are digits and convert them.

Solution

Python
text = "python 456 self learning 89"print([int(w) for w in text.split() if w.isdigit()])
Output
[456, 89]

Learn the concept

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

More string programs

← All 106 String Programs

Similarity of two strings

Python Practice › String Programs › Program 82

Similarity of two strings

MediumString Programs · 82 of 106

Write a Python program to measure how similar two strings are.

Input
"Learning is fun in Sqatools", "Sqatools Online Learning Platform"
Output
Similarity: 0.4
Word overlap (Jaccard): 0.29

Approach

  1. difflib.SequenceMatcher returns a ratio from 0 (different) to 1 (identical).

Solution

Python
from difflib import SequenceMatcher s1 = "Learning is fun in Sqatools"s2 = "Sqatools Online Learning Platform"ratio = SequenceMatcher(None, s1, s2).ratio()print("Similarity:", round(ratio, 2)) w1, w2 = set(s1.lower().split()), set(s2.lower().split())print("Word overlap (Jaccard):", round(len(w1 & w2) / len(w1 | w2), 2))
Output
Similarity: 0.4
Word overlap (Jaccard): 0.29

Line by line

Line 5

The ratio compares matching blocks of characters.

Lines 8-9

A second measure compares shared words over all distinct words.

Note

Different similarity measures give different numbers, so state which one you use.

Learn the concept

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

More string programs

← All 106 String Programs

Remove symbols and capitalise

Python Practice › String Programs › Program 81

Remove symbols and capitalise

EasyString Programs · 81 of 106

Write a Python program to remove unwanted characters from a string and capitalise it.

Input
"sqa****too^^{ls"
Output
Sqatools

Approach

  1. Keep letters only, then capitalize().

Solution

Python
text = "sqa****too^^{ls"print("".join(ch for ch in text if ch.isalpha()).capitalize())
Output
Sqatools

Learn the concept

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

More string programs

← All 106 String Programs

Number of non-empty substrings

Python Practice › String Programs › Program 80

Number of non-empty substrings

EasyString Programs · 80 of 106

Write a Python program to count the non-empty substrings of a string.

Input
"sqatools12"
Output
55
55

Approach

  1. A string of length n has n(n + 1)/2 non-empty substrings.

Solution

Python
text = "sqatools12"n = len(text)print(n * (n + 1) // 2)print(sum(1 for i in range(n) for j in range(i + 1, n + 1)))
Output
55
55

Line by line

Line 3

The formula counts every pair of start and end positions.

Line 4

The nested loops count them one by one and confirm the formula.

Learn the concept

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

More string programs

← All 106 String Programs

Count uppercase, lowercase, digits and specials

Python Practice › String Programs › Program 79

Count uppercase, lowercase, digits and specials

EasyString Programs · 79 of 106

Write a Python program to count the uppercase, lowercase, special and numeric characters in a string.

Input
"@SqaTools.lin"
Output
Special characters: 2
Uppercase characters: 2
Lowercase characters: 9
Numeric values: 0

Approach

  1. Test each character and increase the matching counter.

Solution

Python
text = "@SqaTools.lin"upper = lower = digits = special = 0for ch in text:    if ch.isupper():        upper += 1    elif ch.islower():        lower += 1    elif ch.isdigit():        digits += 1    else:        special += 1print("Special characters:", special)print("Uppercase characters:", upper)print("Lowercase characters:", lower)print("Numeric values:", digits)
Output
Special characters: 2
Uppercase characters: 2
Lowercase characters: 9
Numeric values: 0
Note

“@SqaTools.lin” has 2 special characters (@ and .) and 9 lowercase letters; the original sample showed 1 and 8.

Learn the concept

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

More string programs

← All 106 String Programs

Keep only one given character

Python Practice › String Programs › Program 78

Keep only one given character

EasyString Programs · 78 of 106

Write a Python program to remove all characters except a given one.

Input
"Sqatools python", keep "S"
Output
S

Approach

  1. Keep characters equal to the given one.

Solution

Python
text = "Sqatools python"keep = "S"print("".join(ch for ch in text if ch == keep))
Output
S

Learn the concept

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

More string programs

← All 106 String Programs

Uncommon characters of two strings

Python Practice › String Programs › Program 77

Uncommon characters of two strings

EasyString Programs · 77 of 106

Write a Python program to build a string from the characters that appear in only one of two strings.

Input
"abcdefg", "xyzabcd"
Output
efgxyz

Approach

  1. Keep characters of each string that are not in the other.

Solution

Python
s1, s2 = "abcdefg", "xyzabcd"result = [ch for ch in s1 if ch not in s2] + [ch for ch in s2 if ch not in s1]print("".join(result))
Output
efgxyz

Learn the concept

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

More string programs

← All 106 String Programs

Characters that occur more than once

Python Practice › String Programs › Program 76

Characters that occur more than once

EasyString Programs · 76 of 106

Write a Python program to build a string of the characters that occur more than once.

Input
"aabbcceffgh"
Output
abcf

Approach

  1. Count, then keep characters with a count above 1, in first-seen order.

Solution

Python
from collections import Countertext = "aabbcceffgh"counts = Counter(text)print("".join(ch for ch in counts if counts[ch] > 1))
Output
abcf

Learn the concept

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

More string programs

← All 106 String Programs

Remove consecutive duplicates

Python Practice › String Programs › Program 75

Remove consecutive duplicates

EasyString Programs · 75 of 106

Write a Python program to collapse consecutive duplicate characters into one.

Input
"xxxxyy"
Output
xyx

Approach

  1. Add a character only if it differs from the last one added.

Solution

Python
text = "xxxxyyxx"result = ""for ch in text:    if not result or ch != result[-1]:        result += chprint(result)
Output
xyx

Line by line

Line 4

not result handles the first character.

Note

Only consecutive repeats are removed, so “xxxxyyxx” becomes “xyx”.

Learn the concept

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

More string programs

← All 106 String Programs

Longest run of zeros

Python Practice › String Programs › Program 74

Longest run of zeros

EasyString Programs · 74 of 106

Write a Python program to find the longest run of consecutive 0s in a binary string.

Input
"10001100000111"
Output
5

Approach

  1. Split on “1” and take the longest piece.

Solution

Python
binary = "10001100000111"print(max(len(run) for run in binary.split("1")))
Output
5

Line by line

Line 2

Splitting on “1” leaves only the runs of zeros.

Learn the concept

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

More string programs

← All 106 String Programs