Last updated: Apr 9, 2024
Reading timeยท3 min
for
loopTo check if two strings have the same characters:
sorted()
function to sort the two strings.True
, the two strings have the same
characters.def have_same_characters(str1, str2): return sorted(str1) == sorted(str2) print(have_same_characters('bob', 'obb')) # ๐๏ธ True print(have_same_characters('bob', 'obbb')) # ๐๏ธ False print(have_same_characters('bob', 'abc')) # ๐๏ธ False
The sorted() function takes an iterable and returns a new sorted list from the items in the iterable.
print(sorted('bob')) # ๐๏ธ ['b', 'b', 'o'] print(sorted('obb')) # ๐๏ธ ['b', 'b', 'o']
True
.We sort the characters before comparing, so the order of the characters in the strings is not important.
The function from the code sample returns True
only if the two strings contain
the same characters and have the same length.
for
loopIf you need to check if two strings have the same characters, not considering
the length of the strings and the frequency of each character, use 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('bob', 'obb')) # ๐๏ธ True print(have_same_characters('bob', 'obbbb')) # ๐๏ธ True print(have_same_characters('abc', 'aabbcc')) # ๐๏ธ True print(have_same_characters('bob', 'abc')) # ๐๏ธ False
We used a for
loop to iterate over one of the strings.
On each iteration, we check if the current character is contained in the other string.
If the condition is not met, we return False
from the function right away.
If the condition is met for all characters in the string, the function returns
True
.
This approach only checks if all characters in string A are contained in string B.
The two strings don't have to have the same length for the condition to be met.
You can also use the collections.Counter
class to check if two strings have
the same characters.
from collections import Counter str_1 = 'bob' str_2 = 'obb' if Counter(str_1) == Counter(str_2): # ๐๏ธ this runs print('The strings have the same characters') else: print('The strings do NOT have the same characters')
The
Counter
class from the collections
module is a subclass of the dict
class.
The class is basically a mapping of key-count pairs.
from collections import Counter str_1 = 'bob' str_2 = 'obb' print(Counter(str_1)) # Counter({'b': 2, 'o': 1}) print(Counter(str_2)) # Counter({'b': 2, 'o': 1})
If the Counter
objects contain the same key-count pairs, the two strings
contain the same characters.
You can learn more about the related topics by checking out the following tutorials: