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 Create Pyramid Patterns
Python Program to Print Hello world!
Python hash()
Python Data Analytics with Pandas, NumPy and Matplotlib - Fabio Nelli
Python Program to Convert Celsius To Fahrenheit
Python Program to Display Calendar
Python Program to Reverse a Number
Java Program to Implement the Program Used in grep/egrep/fgrep
Python Program to Find Sum of Natural Numbers Using Recursion
Python Type Conversion and Type Casting
Python List count()
Python type()
Python property()
Python List append()
Python String swapcase()
Python sorted()
Python Set pop()
Python map()
Python String isupper()
Deep Learning with Python - Francois Chollet
Python bytearray()
Python Object Oriented Programming
Python Program to Solve Quadratic Equation
Machine Learning Applications Using Python - Cases studies form Healthcare, Retail, and Finance - Pu...
Python Program to Count the Number of Digits Present In a Number
Python Program to Count the Number of Occurrence of a Character in String
Introduction to Scientific Programming with Python - Joakim Sundnes
Python Program to Compute all the Permutation of the String
Python Modules
Python String rstrip()
Python input()
Python if...else Statement