w3resource

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:

Python String: Count number of substrings with same first and last characters of a given string.

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:

Flowchart: Count number of substrings with same first and last characters of a given string

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.



Follow us on Facebook and Twitter for latest update.