Related Articles

Related Articles

Python sorted() to check if two strings are anagram or not
  • Difficulty Level : Basic
  • Last Updated : 11 May, 2020

Given two strings s1 and s2, check if both the strings are anagrams of each other.

Examples:

Input : s1 = "listen"
        s2 = "silent"
Output : The strings are anagrams.


Input : s1 = "dad"
        s2 = "bad"
Output : The strings aren't anagrams.

Python provides a inbuilt function sorted() which does not modify the original string, but returns sorted string.

Below is the Python implementation of the above approach:



filter_none

edit
close

play_arrow

link
brightness_4
code

# function to check if two strings are
# anagram or not 
def check(s1, s2):
      
    # the sorted strings are checked 
    if(sorted(s1)== sorted(s2)):
        print("The strings are anagrams."
    else:
        print("The strings aren't anagrams.")         
          
# driver code  
s1 ="listen"
s2 ="silent" 
check(s1, s2)

chevron_right


Output:


The strings are anagrams.

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :