How to Check if Two Strings Have the Same Characters in Python?

Estimated read time 2 min read

To check if two strings have the same characters in Python, you can compare them after sorting the characters. Here’s an example:

def have_same_characters(str1, str2):
    # Sort the characters of each string
    sorted_str1 = sorted(str1)
    sorted_str2 = sorted(str2)
    
    # Check if the sorted strings are equal
    if sorted_str1 == sorted_str2:
        return True
    else:
        return False

# Example usage
string1 = "listen"
string2 = "silent"
if have_same_characters(string1, string2):
    print("The strings have the same characters.")
else:
    print("The strings do not have the same characters.")

In this example, the have_same_characters function takes two strings (str1 and str2) as input. The characters of each string are sorted using the sorted() function.

The sorted versions of str1 and str2 are compared using the equality operator (==). If the sorted strings are equal, it means the strings have the same characters, regardless of their original order. The function returns True in this case. Otherwise, it returns False.

Finally, we call the have_same_characters function with example strings “listen” and “silent”. If the strings have the same characters, it prints “The strings have the same characters.” Otherwise, it prints “The strings do not have the same characters.”

Note that this approach is case-sensitive, so uppercase and lowercase characters are considered different. If you want the character check to be case-insensitive, you can convert the strings to lowercase using the lower() method before sorting them.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply