Python Program to Count Repeated Characters in a String

This article is created to cover a program in Python that counts and prints the total number of repeated characters available in a given string entered by the user at run-time.

Count the total number of repeated characters in a string

The question is: write a Python program to count the total number of repeated characters available in a string entered by the user. Here is its answer:

rChar = 0
rCharList = []
k = 0

print("Enter the String: ")
text = str(input())

textList = list(text)
tot = len(text)

for i in range(tot):
  if text[i] in textList:
    if text[i] not in rCharList:
      newText = text[i+1:]
      newTot = len(newText)
      for j in range(newTot):
        if newText[j]==text[i]:
          rChar = rChar+1
          rCharList.insert(k, text[i])
          k = k+1
          break

print("\nTotal Repeated Character(s): ")
print(rChar)

Here is its sample run:

python count repeated characters in string

Now supply the input "codescracker.com" as a string and press the ENTER key to count and print the number of repeated characters available in the given string:

count repeated characters in string python

Note: In the string "codescracker.com", the repeated characters are "c, o, e, r."

To format the output looks of the previous program in a better way, then change the following code:

print("Enter the String: ")

with the statement given below:

print(end="Enter the String: ")

And then the block of code given below:

print("\nTotal Repeated Character(s): ")
print(rChar)

with the following statement:

print("\nTotal Repeated Character(s): " + str(rChar))

After changing these two codes or blocks of code, here is the new output look of the sample run with user input "codescracker" this time:

count repeated characters in string python program

Python Online Test


« Previous Program Next Program »


Liked this post? Share it!