Python Program To Check if Two Strings are Anagrams
In this tutorial, we will discuss a Python program to check if two strings are anagrams.
Before going to the program first, let us understand what is Anagrams.
Anagrams:
- 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.
Related: Python Program to Count the Frequency of Elements in a List
Program code to check if two strings are anagrams in Python
# Check for Anagrams in Python def are_anagrams(str1, str2): return sorted(str1) == sorted(str2) string1 = input("Enter the first string: ") string2 = input("Enter the second string: ") if are_anagrams(string1, string2): print(f"'{string1}' and '{string2}' are anagrams.") else: print(f"'{string1}' and '{string2}' are not anagrams.")
Explanation
- Function Definition: The
are_anagrams
function takes two strings as input and returnsTrue
if they are anagrams, otherwiseFalse
. - Main Program: The program prompts the user to enter two strings and then checks if they are anagrams using the
are_anagrams
function and prints the result.
Output
- When you run the above program, it will prompt you to enter two strings.
- After entering the strings, it will check if they are anagrams and print the result.
Conclusion
- In this tutorial, we learned how to check if two strings are anagrams using a Python program.
- Understanding this concept is essential for text manipulation and enhancing your programming skills.