Python program to check if two strings are anagram

20ITA14 Rupa Shiva Dharshini
2 min readJun 10, 2021

An anagram is a phrase or word that when it’s letters are rearranged, another phrase or word is created.

For example, the word “heart” can be rearranged to form another word “earth”. All the letters must be included while creating anagrams.

Two strings are said to be anagrams, if we can form one from the other by arranging them differently.

Prerequisites:

  1. Knowing about python strings
  2. Knowing about python string functions/methods
  3. The built-in function sorted()

Strings:

A string in python is a collection of characters (or) an array of bytes representing ASCII codes.

Strings in python are surrounded by either single quotation marks, or double quotation marks. Python allows us to use single quotes, double quotes, or triple quotes to create the string.

Example: str1= “hello” , str2= “‘hello’’’…

String functions in python:

  1. The lower() method returns a string where all characters are lower case. Numbers and symbols are ignored. No parameters are required.
  2. This program uses strlen() method/function. This function returns the length of the string. No parameters are required.

sorted() function:

This is a built-in function in python and returns a sorted list of the specified iterable object. We can either sort them in ascending or descending order using ‘reverse’.

Syntax:

sorted(iterable, key, reverse)

Here, the parameters of this function are:

  1. iterable: The iterable to be arranged in ascending or descending order.
  2. key: A function that serves as a key for the sort comparison.(Optional)
  3. reverse: A boolean value. If true, sorts in descending order.(Optional)

Code:

Since Python is case sensitive, we convert the strings to lowercase. (T and t are different in python.)

Then, the strings are sorted and if they are equal; they are anagrams.

Output:

In this program, listen and silent when sorted would have looked like “e, i , l, n, s, t” and they both have the same letters. So, they are anagrams.

To learn python and similar courses:

--

--