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 Deep Learning - Valentino Zocca & Gianmario Spacagna & Daniel Slater & Peter Roelants
Python locals()
Python Set add()
Python Dictionary clear()
Python Program to Differentiate Between type() and isinstance()
Statistical Methods for Machine Learning - Disconver how to Transform data into Knowledge with Pytho...
Python frozenset()
Python Program to Sort a Dictionary by Value
Python Program to Slice Lists
Machine Learning Mastery with Python - Understand your data, create accurate models and work project...
Python String maketrans()
Python timestamp to datetime and vice-versa
Python String startswith()
Python Program to Print Colored Text to the Terminal
Python bool()
Python strftime()
Python Program to Print the Fibonacci sequence
Python Program to Return Multiple Values From a Function
Python Program to Check Whether a String is Palindrome or Not
Python Program to Iterate Over Dictionaries Using for Loop
Python String islower()
Python Set update()
Python Machine Learning Cookbook - Practical solutions from preprocessing to Deep Learning - Chris A...
Python Program to Append to a File
Deep Learning from Scratch - Building with Python form First Principles - Seth Weidman
Intelligent Projects Using Python - Santanu Pattanayak
Python Set union()
Python min()
Python Operators
Python List remove()
Python range()
Python String encode()