Python Program - Check If Two Strings are Anagram

https://‮igi.www‬ftidea.com

Here's a Python program to check if two strings are anagrams:

# take input from the user
str1 = input("Enter the first string: ")
str2 = input("Enter the second string: ")

# check if the strings are of equal length
if len(str1) != len(str2):
    print("The strings are not anagrams.")
else:
    # convert the strings to lowercase
    str1 = str1.lower()
    str2 = str2.lower()

    # sort the characters in both strings
    sorted_str1 = sorted(str1)
    sorted_str2 = sorted(str2)

    # check if the sorted strings are equal
    if sorted_str1 == sorted_str2:
        print("The strings are anagrams.")
    else:
        print("The strings are not anagrams.")

Output:

Enter the first string: Listen
Enter the second string: Silent
The strings are anagrams.

In this program, we take two strings as input from the user using the input() function.

We first check if the strings are of equal length. If they are not, we print a message saying that the strings are not anagrams.

If the strings are of equal length, we convert them to lowercase using the lower() function to ensure that case does not affect the comparison.

We then sort the characters in both strings using the sorted() function and store the sorted strings in variables called sorted_str1 and sorted_str2.

Finally, we check if the sorted strings are equal. If they are, we print a message saying that the strings are anagrams. Otherwise, we print a message saying that the strings are not anagrams.