Hackerss.com

Hackerss.com is a community of amazing hackers

Hackerss is a community for developers, data scientitst, ethical hackers, hardware enthusiasts or any person that want to learn / share their knowledge of any aspect of digital technology.

Create account Log in
hackerss
hackerss

Posted on

Check if two strings are anagram in Python

Check if two strings are anagram - Python:


def anagram(str1, str2):
    """
    Check if two strings are anagrams.

    Parameters
    ----------
    str1 : str
        First string to check.
    str2 : str
        Second string to check.

    Returns
    -------
    bool
        ``True`` if the strings are anagrams, ``False`` otherwise.
    """

    #convert the strings to lower case
    str1 = str1.lower()
    str2 = str2.lower()

    #convert the strings to lists
    list1 = list(str1)
    list2 = list(str2)

    #sort the lists
    list1.sort()
    list2.sort()

    #convert the lists to strings
    str1 = ''.join(list1)
    str2 = ''.join(list2)

    #check if the strings are equal
    if str1 == str2:
        return True
    else:
        return False

#example
result = anagram('dog', 'god')
#output
print(result)  #True
Enter fullscreen mode Exit fullscreen mode

Top comments (0)