Python Tutorials

Python Programs

Python Check If Two Strings are Anagram


Python Check If Two Strings are Anagram

In this tutorial, we will learn how to check if two strings are anagrams in Python. We will cover the basic concept of anagrams and implement a function to perform the check.


What is an Anagram

An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. For example, 'listen' and 'silent' are anagrams.


Syntax

The syntax to check if two strings are anagrams in Python is:

def are_anagrams(str1, str2):
    return sorted(str1) == sorted(str2)


Checking if two strings are anagrams

We can create a function to check if two given strings are anagrams by sorting their characters and comparing the sorted strings.

For example,

  1. Define a function named are_anagrams that takes two parameters str1 and str2.
  2. Use the sorted function to sort the characters of both strings.
  3. Compare the sorted strings. If they are equal, the strings are anagrams.
  4. Return the result of the comparison.
  5. Call the function with sample strings and print the result.

Python Program

def are_anagrams(str1, str2):
    return sorted(str1) == sorted(str2)

# Sample strings
string1 = 'listen'
string2 = 'silent'

# Check if the strings are anagrams
result = are_anagrams(string1, string2)

# Print the result
if result:
    print(f'\'{string1}\' and \'{string2}\' are anagrams')
else:
    print(f'\'{string1}\' and \'{string2}\' are not anagrams')

Output

'listen' and 'silent' are anagrams