Python Practice › String Programs › Program 80
Number of non-empty substrings
Write a Python program to count the non-empty substrings of a string.
Input
"sqatools12"
Output
55 55
Approach
- A string of length n has n(n + 1)/2 non-empty substrings.
Solution
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.