In this example, you will learn to check if two strings are anagram.
To understand this example, you should have the knowledge of the following Python programming topics:
Two strings are said to be anagram if we can form one string by arranging the characters of another string. For example, Race and Care. Here, we can form Race by arranging the characters of Care.
Python program to check if two strings are anagrams using sorted()
str1 = "Race" str2 = "Care" # convert both the strings into lowercase str1 = str1.lower() str2 = str2.lower() # check if length is same if(len(str1) == len(str2)): # sort the strings sorted_str1 = sorted(str1) sorted_str2 = sorted(str2) # if sorted char arrays are same if(sorted_str1 == sorted_str2): print(str1 + " and " + str2 + " are anagram.") else: print(str1 + " and " + str2 + " are not anagram.") else: print(str1 + " and " + str2 + " are not anagram.")
Output
race and care are anagram.
We first convert the strings to lowercase. It is because Python is case sensitive (i.e. R
and r
are two different characters in Python).
Here,
lower()
– converts the characters into lower casesorted()
– sorts both the strings
If sorted arrays are equal, then the strings are anagram.
Related posts:
Introduction to Machine Learning with Python - Andreas C.Muller & Sarah Guido
Python Program to Extract Extension From the File Name
Python Program to Slice Lists
Python Program to Find Armstrong Number in an Interval
Python super()
Python delattr()
Python enumerate()
Python Program to Display Fibonacci Sequence Using Recursion
Python Program to Sort a Dictionary by Value
Python vars()
Python Data Analytics with Pandas, NumPy and Matplotlib - Fabio Nelli
Python break and continue
Python setattr()
Python Program to Differentiate Between type() and isinstance()
Python Program to Solve Quadratic Equation
Python Data Structures and Algorithms - Benjamin Baka
Python memoryview()
Building Chatbots with Python Using Natural Language Processing and Machine Learning - Sumit Raj
Python Program to Display the multiplication Table
Python str()
How to Get Started With Python?
Python format()
Python List remove()
Python Set clear()
Python Program to Access Index of a List Using for Loop
Python String rpartition()
Python String maketrans()
Python Dictionary keys()
Building Machine Learning Systems with Python - Willi Richert & Luis Pedro Coelho
Python Program to Create a Countdown Timer
Python Global Keyword
Python Anonymous / Lambda Function