Python Programs | IT Developer
IT Developer

Python Programs



Share with a Friend

Python Programs - String

Check if two strings are anagrams - Python Program

Example 1 :

def is_anagram(s1, s2): return sorted(s1.replace(" ", "").lower()) == sorted(s2.replace(" ", "").lower()) print(is_anagram("listen", "silent"))

Output

 
OUTPUT  :
True

Example 2 :

def check_anagrams(str1, str2): """ Checks if two strings are anagrams of each other. Args: str1: The first string. str2: The second string. Returns: True if the strings are anagrams, False otherwise. """ # 1. Normalize the strings (convert to lowercase) s1 = str1.lower() s2 = str2.lower() # 2. Check if the lengths are equal if len(s1) != len(s2): return False # 3. Sort the characters in both strings sorted_s1 = sorted(s1) sorted_s2 = sorted(s2) # 4. Compare the sorted strings return sorted_s1 == sorted_s2 # Test cases string1 = "Listen" string2 = "Silent" string3 = "Hello" string4 = "World" print(f"'{string1}' and '{string2}' are anagrams: {check_anagrams(string1, string2)}") print(f"'{string3}' and '{string4}' are anagrams: {check_anagrams(string3, string4)}") # User input example user_string1 = input("Enter the first string: ") user_string2 = input("Enter the second string: ") if check_anagrams(user_string1, user_string2): print(f"'{user_string1}' and '{user_string2}' are anagrams!") else: print(f"'{user_string1}' and '{user_string2}' are not anagrams.")

Output

 
OUTPUT  :
'Listen' and 'Silent' are anagrams: True
'Hello' and 'World' are anagrams: False
Enter the first string: Listen
Enter the second string: Silent
'Listen' and 'Silent' are anagrams!