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.

Advertisement
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

Leave a Comment