Python Program to check if two strings are anagrams


April 6, 2022, Learn eTutorial
1338

In this simple python program, we need to check the strings are anagrams. It is a number-based python program.

For a better understanding of this example, we always recommend you to learn the basic topics of Python programming listed below:

What are anagram strings?

In this python program, we have to check the given strings are anagram or not. Anagram strings are two strings built up by the same set of characters, where the order of characters is the only difference in the strings. For example, the word 'silent' and 'listen' are anagrams, or 'peek' and 'keep' are anagrams.

What are anagram strings?

How to check anagram strings in python?

So here we are taking the strings from the user and checking the strings are made of the same set of characters. We sort the characters in ascending order and then compare the sorted strings that are the same or not. If the strings are the same, then print the given strings are Anagram else they are not anagrams.

Note: Using sort() function, a built-in function in the python programming language is used to sort the data and return the sorted data in ascending order as default.

ALGORITHM

STEP 1: Accept the two strings from the user using the input function and save that two strings in two variables.

STEP 2: Using the sort() built-in function in python language, we sort the words of two strings. And then using if condition check if the sorted strings are the same or not.

STEP 3: If the condition satisfies, then display the strings are anagrams else display the strings are not anagrams using print statements in the python programming language.

Python Source Code

                                          s1=input("Enter first string:")
s2=input("Enter second string:")
if(sorted(s1)==sorted(s2)):
      print("The strings are anagrams.")
else:
      print("The strings aren't anagrams.")
                                      

OUTPUT

Enter first string : keep
Enter second string : peek

The strings are anagrams