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:
Python Program to Count the Number of Occurrence of a Character in String
Building Chatbots with Python Using Natural Language Processing and Machine Learning - Sumit Raj
Python Program to Solve Quadratic Equation
Python Program to Transpose a Matrix
Python Matrices and NumPy Arrays
Python Program to Parse a String to a Float or Int
Python Program to Compute all the Permutation of the String
Python Program to Calculate the Area of a Triangle
Python List copy()
Python Program to Get Line Count of a File
Python str()
Python Generators
Python Program to Find Hash of File
Python Package
Python List insert()
Python Statement, Indentation and Comments
Python Program to Convert Decimal to Binary Using Recursion
Python float()
Python staticmethod()
Python List
Python Dictionary update()
Python Set clear()
Python Program to Copy a File
Python Program to Display Powers of 2 Using Anonymous Function
Python Program to Append to a File
Python String ljust()
Python Numbers, Type Conversion and Mathematics
Python Custom Exceptions
Python String rstrip()
Python Set add()
Python object()
Python Exception Handling Using try, except and finally statement