Find repeated characters in a string in Python
In this tutorial, we will look into how to find repeated characters in a string in Python, which is a beneficial task when talking about strings and their repetition.
Most of the time, when we work on strings, we need to find the character which is repeated many times in a string.
The input and output must be in such a manner that the string is the input and the output shows the list of characters repeated.
Input- CodeSpeedy Output- d,e
There is not a single way of doing this task, we can do it in multiple ways. Here’s the first one-
Using dictionary and for loop to find repeated characters
We will create an empty dictionary where we will store each character with its count and then we will check using a for loop if any character has more than count 1, we will print that. Here’s the snippet part-
str = "CodeSpeedy" count = {} for i in str: if i in count: count[i] += 1 else: count[i] = 1 for j in count: if count[j] > 1: print(j, count[j])
d 2 e 3
Find and count repeated characters in a string using counter
We can also do it in another way using a counter which holds the character and its count found under Collections. Here’s the implementation-
from collections import Counter str="CodeSpeedy" word=Counter(str) for i,count in word.items(): if(count>1): print(i,count)
d 2 e 3
We have found the repeated characters in a string in multiple ways. I hope you like this tutorial. Thanks for reading!
Leave a Reply