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 hasattr()
Python Dictionary copy()
Python 3 for Absolute Beginners - Tim Hall & J.P Stacey
Building Chatbots with Python Using Natural Language Processing and Machine Learning - Sumit Raj
Python Program to Differentiate Between type() and isinstance()
Python *args and **kwargs
Python bool()
Python datetime
Python String isdigit()
Python Program to Trim Whitespace From a String
Python Program to Make a Simple Calculator
Python Modules
Python exec()
Python Inheritance
Introduction to Machine Learning with Python - Andreas C.Muller & Sarah Guido
Python List extend()
Python Dictionary fromkeys()
Python frozenset()
Python next()
Natural Language Processing with Python - Steven Bird & Ewan Klein & Edward Loper
Python Variables, Constants and Literals
Node.js vs Python for Backend Development
Python Program to Sort a Dictionary by Value
Python String rjust()
Python Program to Convert Kilometers to Miles
Python Set difference()
Python Package
Python input()
Python Exception Handling Using try, except and finally statement
Machine Learning Mastery with Python - Understand your data, create accurate models and work project...
Python format()
Python Data Structures and Algorithms - Benjamin Baka