How to Detect If Two Strings are Anagram in Python


This example will teach us how to determine whether two strings are an anagram in Python.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

str1 = input("Please input the first string: ")
str2 = input("Please input the second string: ")
if sorted(str1) == sorted(str2):
      print("The strings are anagrams.")
else:
      print("The strings aren't anagrams.")

Output:

Case 1:
Please input the first string: earth
Please input the second string: heart
The strings are anagrams.

Case 2:
Please input the first string: listen
Please input the second string: hello
The strings aren't anagrams.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Advertisement