Check if Two Strings are Anagrams in Python
Introduction
This program checks if two strings are anagrams of each other. Two strings are considered anagrams if they contain the same characters with the same frequencies, but possibly in a different order.
Python Program
def are_anagrams(str1, str2):
"""
Check if two strings are anagrams.
:param str1: The first string.
:param str2: The second string.
:return: True if the strings are anagrams, False otherwise.
"""
# Remove any spaces and convert strings to lowercase
str1 = str1.replace(" ", "").lower()
str2 = str2.replace(" ", "").lower()
# Check if lengths of both strings are equal
if len(str1) != len(str2):
return False
# Sort both strings and compare
return sorted(str1) == sorted(str2)
def main():
"""
Main function to test the are_anagrams function.
"""
# Example strings
string1 = "Listen"
string2 = "Silent"
# Check if the strings are anagrams
if are_anagrams(string1, string2):
print(f'"{string1}" and "{string2}" are anagrams.')
else:
print(f'"{string1}" and "{string2}" are not anagrams.')
if __name__ == "__main__":
main()
Explanation
The program consists of two functions:
are_anagrams
: This function takes two strings as input and returns a boolean indicating whether they are anagrams. It performs the following steps:- Removes any spaces and converts both strings to lowercase to ensure case-insensitive comparison.
- Checks if the lengths of both strings are equal. If not, they cannot be anagrams.
- Sorts both strings and compares them. If the sorted versions are identical, the strings are anagrams.
main
: This function serves as the entry point of the program. It defines two example strings, calls theare_anagrams
function to check if they are anagrams, and prints the result.
Key Points:
- The program removes spaces and converts strings to lowercase to handle case and space insensitivity.
- Sorting is used to compare the strings, as anagrams will have identical sorted character sequences.
- The
main
function demonstrates the use of theare_anagrams
function with example strings.