Check if two strings have the same characters in Python

avatar

Borislav Hadzhiev

Last updated: Sep 18, 2022

banner

Photo from Unsplash

Check if two strings have the same characters in Python #

To check if two strings have the same characters:

  1. Use the sorted() function to sort the two strings.
  2. Use the equality operator to compare the results.
  3. If the comparison evaluates to True, the two strings have the same characters.
main.py
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.

main.py
print(sorted('bob')) # 👉️ ['b', 'b', 'o'] print(sorted('obb')) # 👉️ ['b', 'b', 'o']
If the two strings have the same length and contain the same characters the comparison evaluates to 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.

If 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.
main.py
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.

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.