Check if a character appears twice in a String in Python

avatar

Borislav Hadzhiev

Last updated: Sep 20, 2022

banner

Photo from Unsplash

Check if a character appears twice in a String in Python #

Use the str.count() method to check if a character appears twice in a string, e.g. if my_str.count(char) == 2:. The str.count() method returns the number of occurrences of a substring in a string.

main.py
my_str = 'bobbyhadz.com' # ✅ Check if a character appears twice in string if my_str.count('o') == 2: # 👇️ this runs print('The character appears twice in the string') else: print('The character does NOT appear twice in the string') print(my_str.count('o')) # 👉️ 2 print(my_str.count('.')) # 👉️ 1 print(my_str.count('b')) # 👉️ 3 # --------------------------------------------------- # ✅ Check if string has repeated characters my_str = 'bobby' has_repeated_chars = len(set(my_str)) != len(my_str) print(has_repeated_chars) # 👉️ True my_str = 'abc' has_repeated_chars = len(set(my_str)) != len(my_str) print(has_repeated_chars) # 👉️ False

The str.count method returns the number of occurrences of a substring in a string.

main.py
my_str = 'bobbyhadz.com' if my_str.count('o') == 2: # 👇️ this runs print('The character appears twice in the string') else: print('The character does NOT appear twice in the string') print(my_str.count('o')) # 👉️ 2 print(my_str.count('.')) # 👉️ 1 print(my_str.count('b')) # 👉️ 3 print(my_str.count('X')) # 👉️ 0

If the method returns 2, then the character appears twice in the string.

If you need to check if the string has repeated characters, convert the string to a set and compare the length of the set to the string's length.
main.py
my_str = 'bobby' has_repeated_chars = len(set(my_str)) != len(my_str) print(has_repeated_chars) # 👉️ True my_str = 'abc' has_repeated_chars = len(set(my_str)) != len(my_str) print(has_repeated_chars) # 👉️ False

We used the set() class to convert the string to a set object.

Set objects are an unordered collection of unique elements, so any duplicate characters get removed when converting to a set.

If the length of the set is not equal to the string's length, then the string has repeated characters.

You can also use a for loop to check if a string contains repeated characters.

main.py
my_str = 'bobby' def has_repeated_chars(string): for char in string: if string.count(char) > 1: return True return False print(has_repeated_chars('bobby')) # 👉️ True print(has_repeated_chars('abc')) # 👉️ False

On each iteration, we use the str.count() method to check if the character appears more than once in the string.

If the condition is met, we return True and exit out of the function.

If the condition is never met, the string doesn't contain any repeated characters and False is returned.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.