Python program to check if two Strings are Anagram or not

Check if The Two Strings are Anagram or not

Anagram program in python is when strings share the same no of characters and also the same characters then strings are called anagrams. The rearrangement of similar characters or letters in a string even if they don’t have the same meanings are anagrams. Only one strict rule is followed if we create anagrams of a string ‘count of every character available in the 1st string should be equal to the count of characters in the 2nd string for the same character.

Python program to check if two Strings are Anagram or not

Anagram Program in Python

Two strings S1 and S2 are anagrams of one another if –

By re-arranging characters of string1 (s1) we can form string2 (s2) and vice versa

Python program to check if two Strings are Anagram or not

Check if two Strings are Anagram or not in Python

Algorithm

  • Method 1: Sorts both string and check if the results are same or not
  • Method 2: Uses counter method that gives results of individual counts of items present in the list, and compare them

Method 1

  • This method first converts both strings into lowercase
  • We sort both of the strings
  • We then compare both resultant strings
  • If they are same then they must be anagrams
# Anagram program in python
# take user input String1 = "Listen" String2 = "Silent" String1 = sorted(String1.lower()) String2 = sorted(String2.lower()) print("String1 after sorting: ", String1) print("String2 after sorting: ", String2) # check if now strings matches if String1 == String2: print('Strings are anagram') else: print('Strings are not anagram')

Output:

String1 after sorting:  ['e', 'i', 'l', 'n', 's', 't']
String2 after sorting:  ['e', 'i', 'l', 'n', 's', 't']
Strings are anagram

Method 2

We use counter method from the collections library for this.

The counter method can be used as –

  • For string: Listen
  • Counter(string)

printing this counter string will give a result –

Counter({'l': 1, 'i': 1, 's': 1, 't': 1, 'e': 1, 'n': 1})

We can then compare both counters for both the strings.

# Check if two Strings are Anagram or not in Python
from collections import Counter def check(s1, s2): # printing counter print(Counter(s1)) print(Counter(s2)) # implementing counter function if Counter(s1) == Counter(s2): print("The strings are anagrams.") else: print("The strings aren't anagrams.") # driver code s1 = "Listen" s2 = "silent" check(s1.lower(), s2.lower())

Output:

Counter({'l': 1, 'i': 1, 's': 1, 't': 1, 'e': 1, 'n': 1})
Counter({'s': 1, 'i': 1, 'l': 1, 'e': 1, 'n': 1, 't': 1})
The strings are anagrams.

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

  • Length of the string without using strlen() function : C | C++ | Java | Python
  • Toggle each character in a string : C | C++ | Java | Python
  • Count the number of vowels : C | C++ | Java | Python
  • Remove the vowels from a String : C | C++ | Java | Python
  • Check if the given string is Palindrome or not : C | C++ | Java | Python
  • Print the given string in reverse order : C | C++ | Java | Python
  • Remove all characters from string except alphabets : C | C++ | Java | Python
  • Remove spaces from a string : C | C++ | Java | Python
  • Remove brackets from an algebraic expression : C | C++ | Java | Python
  • Count the sum of numbers in a string : C | C++ | Java | Python
  • Capitalize the first and last character of each word of a string : C | C++ | Java | Python
  • Calculate frequency of characters in a string : C | C++ | Java | Python
  • Find non-repeating characters in a string : C | C++ | JAVA | Python
  • Check if two strings are Anagram or not : C | C++ | Java | Python
  • Replace a sub-string in a string: C | C++ | Java | Python
  • Count common sub-sequence in two strings : C | C++ | Java | Python
  • Check if two strings match where one string contains wildcard characters : C | C++ | Java | Python

7 comments on “Python program to check if two Strings are Anagram or not”


  • Yash

    st1=’silent’
    st2=’listn’
    def check(st1,st2):
    for i in st1:
    if i in st2:
    st2=st2.replace(i,”)
    else:
    return False
    return True
    print(check(st1,st2))


  • Mohit

    #USING SIMPLE IF ELSE CONDITIONS
    a=set(input().lower())
    b=set(input().lower())
    # flag=True
    if(len(a)==len(b)):
    for i in a:
    if(i in b):
    flag=True
    else:
    flag=False
    break
    if(flag):
    print(“yes”)
    else:
    print(“no”)


  • SUMAN

    from collections import Counter
    def anagram(s):
    return Counter(s);
    s1,s2 = input().split(“,”);
    str1 = anagram(s1);
    str2 = anagram(s2);
    if str1==str2 :
    print(“Anagram”);
    else :
    print(“Not anagram”);


  • SUMAN

    s1,s2 = input().split(“,”);
    str1 = sorted(s1.lower());
    str2 = sorted(s2.lower());
    if str1 == str2 :
    print(“anagram”);
    else :
    print(“Not anagram”);


  • nidhisingh151199

    s1=input()
    s2=input()
    l1=[]
    l2=[]
    for i in s1:
    l1.append(i.lower())
    l1.sort()
    for j in s2:
    l2.append(j.lower())
    l2.sort()
    if(l1==l2):
    print(“A”)
    else:
    print(“n”)


  • nagavasavi2002

    a=input()
    b=input()
    a=sorted(a.lower())
    b=sorted(b.lower())
    print(a)
    print(b)
    if(a==b):
    print(“strings are anagram”)
    else:
    print(“strings are not anagram”)


  • 44_Harsh

    a = str(input(“enter first string :”))
    b = str(input(“enter second string: “))
    a =list(a)
    b =list(b)
    a.sort()
    b.sort()
    if a ==b:
    print(“valid”)
    else:
    print(“invalid”)
    #OUTPUT
    enter first string :prepinsta
    enter second string: preepinsta
    invalid