Python: Count number of substrings with same first and last characters of a given string
Python String: Exercise-80 with Solution
Write a Python program to count the number of substrings with the same first and last characters in a given string.
Visual Presentation:
Sample Solution:
Python Code:
# Function to count substrings with equal ends
def no_of_substring_with_equalEnds(str1):
result = 0;
# Get string length
n = len(str1);
# Generate all substrings
for i in range(n):
for j in range(i, n):
# Check if ends are equal
if (str1[i] == str1[j]):
result = result + 1
return result
# Get input string
str1 = input("Input a string: ")
# Print result
print(no_of_substring_with_equalEnds(str1))
Sample Output:
Input a string: abc 3
Flowchart:
Python Code Editor:
Previous: Write a Python program to find smallest and largest word in a given string.
Next: Write a Python program to find the index of a given string at which a given substring starts. If the substring is not found in the given string return 'Not found'.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
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://w3resource.com/python-exercises/string/python-data-type-string-exercise-80.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics