How to Check if Two Strings Have the Same Characters in Python
This guide explores different ways to determine if two strings in Python contain the same characters. We'll cover two main scenarios:
- Same Characters, Any Order, Same Counts: The strings must have the same characters, and each character must appear the same number of times, but the order doesn't matter (e.g., "bob" and "obb" are considered the same).
- Same Characters, Any Order, Any Counts: The strings must have the same set of characters, but the number of times each character appears can be different (e.g., "bob" and "obbbb" have the same characters).
We'll use sorted()
, collections.Counter
, and a for
loop to illustrate the different approaches.
Same Characters, Same Counts, Any Order (Anagrams)
This is the most common interpretation of "same characters". The strings must have the same characters, and each character must appear the same number of times. The order doesn't matter.
Using sorted()
(Recommended)
The simplest and often fastest way is to sort both strings and compare the results:
def have_same_characters(str1, str2):
return sorted(str1) == sorted(str2)
print(have_same_characters('tut', 'ttu')) # Output: True
print(have_same_characters('tut', 'uttt')) # Output: False
print(have_same_characters('tut', 'abc')) # Output: False
print(have_same_characters('tut', 'ttu')) # Output: True
sorted(str1)
: Converts the stringstr1
into a list of characters, sorted alphabetically.==
: Compares the two sorted lists. If the strings have the same characters with the same counts, the sorted lists will be identical.
This method is very efficient because sorting is generally fast (Python uses the Timsort algorithm), and list comparison is also fast.
Using collections.Counter
(Also Good)
collections.Counter
provides another concise and efficient way to solve this problem:
from collections import Counter
str_1 = 'tut'
str_2 = 'utt'
if Counter(str_1) == Counter(str_2):
print('The strings have the same characters')
else:
print('The strings do NOT have the same characters')
Output:
The strings have the same characters
Counter(str1)
: Creates aCounter
object, which is a dictionary-like object that stores the counts of each character in the string.==
: Comparing twoCounter
objects checks if they have the same characters and counts.- This approach is efficient and readable.
Same Characters, Any Counts, Any Order
This scenario is less common. Here, you only care that the set of characters is the same, regardless of how many times each character appears.
Using a for
loop
def have_same_characters(str1, str2):
for char in str1:
if not char in str2:
return False
return True
print(have_same_characters('tut', 'utt')) # Output: True
print(have_same_characters('tut', 'utttt')) # Output: True
print(have_same_characters('abc', 'aabbcc')) # Output: True
print(have_same_characters('tut', 'abc')) # Output: False
- This checks that all of the characters of the first string are present in the second string.