w3resource

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

Python String: Exercise-77 with Solution

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

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/python-exercises/string/python-data-type-string-exercise-77.php