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:
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.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics