Python | Ways to check string contain all same characters
Last Updated :
14 Mar, 2023
Given a list of strings, write a Python program to check whether each string has all the characters same or not. Given below are a few methods to check the same.
Method #1: Using Naive Method [Inefficient]
Python3
# Python code to demonstrate
# to check whether string contains
# all characters same or not
# Initialising string list
ini_list = ["aaaaaaaaaaa", "aaaaaaabaa"]
# Printing initial string
print("Initial Strings list", ini_list)
# Using Naive Method:
flag = True
for i in ini_list:
for j in range(0, len(i)-1):
if i[j] != i[j + 1]:
print("String {} don't have all characters same".format(i))
flag = False
break
if flag == True:
print("String {} have all characters same".format(i))
OutputInitial Strings list ['aaaaaaaaaaa', 'aaaaaaabaa']
String aaaaaaaaaaa have all characters same
String aaaaaaabaa don't have all characters same
Time Complexity: O(n^2), where n is the length of the longest string in the list.
Auxiliary Space: O(1), as the code only uses a few variables and does not store any additional data.
Method #2: Using String Comparisons
Python3
# Python code to demonstrate
# to check whether string contains
# all characters same or not
# Initialising string list
ini_list = ["aaaaaaaaaaa", "aaaaaaabaa"]
# Printing initial string
print("Initial Strings list", ini_list)
# Using String comparison
for i in ini_list:
if i == len(i)*i[0]:
print("String {} have all characters same".format(i))
else:
print("String {} don't have all characters same".format(i))
OutputInitial Strings list ['aaaaaaaaaaa', 'aaaaaaabaa']
String aaaaaaaaaaa have all characters same
String aaaaaaabaa don't have all characters same
Time Complexity: O(n) where n is the length of the string.
Auxiliary Space: O(1) as we are using only a variable to store the first character of the string and compare it with other characters.
Method #3: Using count comparison
Python3
# Python code to demonstrate
# to check whether string contains
# all characters same or not
# Initialising string list
ini_list = ["aaaaaaaaaaa", "aaaaaaabaa"]
# Printing initial string
print("Initial Strings list", ini_list)
# Using String comparison
for i in ini_list:
if i.count(i[0]) == len(i):
print("String {} have all characters same".format(i))
else:
print("String {} don't have all characters same".format(i))
OutputInitial Strings list ['aaaaaaaaaaa', 'aaaaaaabaa']
String aaaaaaaaaaa have all characters same
String aaaaaaabaa don't have all characters same
Time complexity: O(n), where n is the number of strings in the list ini_list.
Auxiliary space: O(1), as the space used is constant regardless of the size of the input.
Method #4 : Using len() and set() methods
Python3
# Python code to demonstrate
# to check whether string contains
# all characters same or not
# Initialising string list
ini_list = ["aaaaaaaaaaa", "aaaaaaabaa"]
# Printing initial string
print("Initial Strings list", ini_list)
# Using Naive Method:
flag = True
for i in ini_list:
a = len(set(i))
if(a == 1):
print("String {} have all characters same".format(i))
else:
print("String {} don't have all characters same".format(i))
OutputInitial Strings list ['aaaaaaaaaaa', 'aaaaaaabaa']
String aaaaaaaaaaa have all characters same
String aaaaaaabaa don't have all characters same
The time complexity of this code is O(n*m) where n is the length of the list ini_list and m is the length of the longest string in the list.
The auxiliary space complexity of this code is O(1), as we are not using any extra space to store intermediate results.
Method #5 : Using all()
Here's an example of using the built-in all() function to check if a given string contains all the same characters in Python:
In this example, we first initialize a list of strings called ini_list and print it to show the original list of strings. We then use the all() function along with a generator expression to check if all characters in the input string are the same. The generator expression iterates through each character in the input string, comparing it to the first character of the input string.
The all() function returns True if all elements in the input iterable are True, and False otherwise. If the result of the all() function is True, it means that the input string contains all the same characters, and if the result is False, it means that the input string does not contain all the same characters.
Python3
# Initialising string list
ini_list = ["aaaaaaaaaaa", "aaaaaaabaa"]
# Printing initial string
print("Initial Strings list", ini_list)
# Using all() method
for i in ini_list:
result = all(c == i[0] for c in i)
if result:
print("String {} have all characters same".format(i))
else:
print("String {} don't have all characters same".format(i))
#This code is contributed by Edula Vinay Kumar Reddy
OutputInitial Strings list ['aaaaaaaaaaa', 'aaaaaaabaa']
String aaaaaaaaaaa have all characters same
String aaaaaaabaa don't have all characters same
Time Complexity: O(n) where n is the length of the input string. This is because the method iterates through the input string once to compare each character with the first character of the input string.
Auxiliary Space: O(1) as it doesn't consume any extra space.
Similar Reads
Check if string contains character - Python
We are given a string and our task is to check if it contains a specific character, this can happen when validating input or searching for a pattern. For example, if we check whether 'e' is in the string 'hello', the output will be True.Using in Operatorin operator is the easiest way to check if a c
2 min read
Python program to check a string for specific characters
Here, will check a string for a specific character using different methods using Python. In the below given example a string 's' and char array 'arr', the task is to write a python program to check string s for characters in char array arr. Examples: Input: s = @geeksforgeeks% arr[] = {'o','e','%'}O
4 min read
Python - Test if String contains any Uppercase character
The goal is to check if a given string contains at least one uppercase letter (A-Z). Using any() and isupper()any() function, combined with isdigit(), checks if any character in a string is a digit. It efficiently scans the string and returns True if at least one digit is found.Python# Define the in
3 min read
Python - Similar characters Strings comparison
Given two Strings, separated by delim, check if both contain same characters. Input : test_str1 = 'e!e!k!s!g', test_str2 = 'g!e!e!k!s', delim = '!' Output : True Explanation : Same characters, just diff. positions. Input : test_str1 = 'e!e!k!s', test_str2 = 'g!e!e!k!s', delim = '!' Output : False Ex
6 min read
Python - Key with all Characters in String
Sometimes, while working with Python Strings, we can have problem in which we need to extract all the keys that have all the characters of given some random key. This kind of problem has application has many domains such as day-day programming. Let's discuss a way in which this problem can be solved
3 min read
Test if String Contains Alphabets and Spaces - Python
We are given a string and the task is to determine whether it contains only alphabets and spaces, this is often required when working with datasets where the string must not include any digits, punctuation or special characters.Using all() isspace() and isalpha()This method iterates through each cha
3 min read
Python - Strings with all given List characters
GIven Strings List and character list, extract all strings, having all characters from character list. Input : test_list = ["Geeks", "Gfg", "Geeksforgeeks", "free"], chr_list = [ 'f', 'r', 'e'] Output : ['free', "Geeksforgeeks"] Explanation : Only "free" and "Geeksforgeeks" contains all 'f', 'r' and
4 min read
Count the number of characters in a String - Python
The goal here is to count the number of characters in a string, which involves determining the total length of the string. For example, given a string like "GeeksForGeeks", we want to calculate how many characters it contains. Letâs explore different approaches to accomplish this.Using len()len() is
2 min read
Python | Strings with similar front and rear character
Sometimes, while programming, we can have a problem in which we need to check for the front and rear characters of each string. We may require to extract the count of all strings with similar front and rear characters. Let's discuss certain ways in which this task can be performed. Method #1: Using
4 min read
Python | Kth index character similar Strings
Sometimes, we require to get the words that have the Kth index with the specific letter. This kind of use case is quiet common in places of common programming projects or competitive programming. Letâs discuss certain shorthand to deal with this problem in Python. Method #1: Using list comprehension
3 min read