w3resource

Python: Count number of non-empty substrings of a given string


Count non-empty substrings.

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

Sample Solution:

Python Code:

# Function to count substrings
def number_of_substrings(str):

  # Get length of string
  str_len = len(str);  

  # Formula to calculate substrings
  return int(str_len * (str_len + 1) / 2);

# Get input string
str1 = input("Input a string: ")

# Print result  
print("Number of substrings:")
print(number_of_substrings(str1)) 

Sample Output:

Input a string:  w3resource
Number of substrings:
55

Flowchart:

Flowchart: Count number of non-empty substrings of a given string

For more Practice: Solve these Related Problems:

  • Write a Python program to calculate the total number of non-empty substrings in a given string using a mathematical formula.
  • Write a Python program to generate all non-empty substrings of a string and return their count.
  • Write a Python program to implement a recursive function that counts all possible non-empty substrings of an input string.
  • Write a Python program to use combinatorial logic to compute the number of substrings based on the string length.

Python Code Editor:

Previous: Write a Python program to count number of substrings from a given string of lowercase alphabets with exactly k distinct (given) characters.
Next: Write a Python program to count characters at same position in a given string (lower and uppercase characters) as in English alphabet.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.