w3resource

Python Challenges: Check if a given string is an anagram of another given string


Write a Python program to check if a given string is an anagram of another given string.

According to Wikipedia an anagram is direct word switch or word play, the result of rearranging the letters of a word or phrase to produce a new word or phrase, using all the original letters exactly once; for example, the word anagram can be rearranged into nag-a-ram.

Explanation:

Python: Check if a given string is an anagram of another given string

Sample Solution:

Python Code:

def is_anagram(str1, str2):
    list_str1 = list(str1)
    list_str1.sort()
    list_str2 = list(str2)
    list_str2.sort()

    return (list_str1 == list_str2)

print(is_anagram('anagram','nagaram'))
print(is_anagram('cat','rat'))

Sample Output:

True
False

Flowchart:

Python Flowchart: Check if a given string is an anagram of another given string

Python Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Python program to get the Hamming numbers upto a given numbers also check whether a given number is an Hamming number.
Next: Write a Python program to push all zeros to the end of a list.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.