Python Program to Check If Two Strings are Anagram Ad Sponsored

ⓘ Sponsored by

An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, using all the original letters exactly once. For example, the words “listen” and “silent” are anagrams of each other because they use the same letters in different orders.

In order for two words or phrases to be considered anagrams, they must have the same number of letters, and each letter must appear the same number of times in both words or phrases. For example, “elbow” and “below” are not anagrams because they have a different number of letters, and “racecar” and “carerace” are not anagrams because they do not have the same number of each letter.

Python Code :

The Below Python program checks if two strings are anagrams:

string1 = 'silent'
string2 = 'listen'

# Convert the strings to lowercase and remove whitespace
string1 = string1.lower().replace(' ', '')
string2 = string2.lower().replace(' ', '')

# Check if the lengths of the strings are equal
if len(string1) != len(string2):
    print('The strings are not anagrams')
    # Convert the strings to lists and sort them
    list1 = sorted(list(string1))
    list2 = sorted(list(string2))

    # Check if the sorted lists are equal
    if list1 == list2:
        print('The strings are anagrams')
        print('The strings are not anagrams')

This program first asks the user to enter two strings. Then it converts both strings to lowercase and removes any spaces in them.

Next, the program sorts the characters in each string using the sorted() function. The sorted() function returns a new list that contains the sorted elements of the original list.

Finally, the program compares the sorted strings using the == operator. If the sorted strings are equal, then the original strings are anagrams. Otherwise, the original strings are not anagrams. The program prints the appropriate message based on the comparison result. Ad Sponsored

ⓘ Sponsored by