Skip to content
How to Compare Two Strings for Identical Characters in Python
Fundamentals 2 min read

How to Compare Two Strings for Identical Characters in Python

This article shows how to determine whether two strings contain the same set of characters in Python, presenting two approaches—using set comparison and the all() function with length checks—and provides complete code examples for each method.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations

Student asked how to determine whether the elements in two strings a and b are identical, outputting True if they match and False otherwise.

Coach’s analysis: the task is to check if the sets of characters are the same, treating repeated characters only once.

Method 1 – Using a set

a = "abcd31d111111"
b = "3acdb1"
print(set(a) == set(b))
# >>> True

Method 2 – Using all() with length check

a = "abcd31d111111"
b = "3acdb1"
long_ = a if len(a) > len(b) else b
short_ = a if len(a) < len(b) else b
result = all([short_.count(x) for x in long_])
print(result)
# >>> True

The all() approach first selects the longer and shorter strings, then verifies that every character in the longer string appears in the shorter one.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Pythonprogramming basicsset__all__string-comparison
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.