pythonanagram

How can I check if two strings are anagrams of each other?


I am trying to write a program that accepts two strings from the user:

s1 = input("Please enter a word:")
s2 = input("Please enter another word:")

How can I output True if the two are anagrams and False otherwise?


If you found this question from a search engine and want to look for possibly multiple anagrams within a list: it is possible, but not optimal to compare each pair of elements. Please see Using Python, find anagrams for a list of words for more specific advice.


Solution

  • You need to think through your conditional logic a bit more. The loop is on the right track, but if there is a letter in s1 that is NOT in s2, you should break out of this loop and print the "False" statement. Consider using a variable like all_s1_in_s2 = True and then setting that to false if you find a letter that doesn't match.

    Some other tips: