Converting strings to sets enables efficient deduplication and fast membership testing. Sets automatically remove duplicates and provide O(1) lookup time, making them ideal for checking unique elements.
Extract Unique Characters with set()
Pass a string directly to set() to get unique characters.
text = "hello"
unique_chars = set(text)
print(unique_chars)
print(len(unique_chars))Analyze Character Composition
password = "aB3$aB3$xY"
unique = set(password)
print(f"Unique characters: {len(unique)}")
has_digit = bool(unique & set('0123456789'))
has_upper = bool(unique & set('ABCDEFGHIJKLMNOPQRSTUVWXYZ'))
has_special = bool(unique & set('!@#$%^&*'))
print(f"Has digit: {has_digit}") # True
print(f"Has uppercase: {has_upper}") # True
print(f"Has special: {has_special}") # TrueOutput:
Unique characters: 6
Has digit: True
Has uppercase: True
Has special: TrueExtract Unique Words with split()
Combine split() and set() to find unique words in text.
text = "apple orange banana apple orange grape"
unique_words = set(text.split())
print(unique_words)
print(f"Total words: {len(text.split())}")
print(f"Unique words: {len(unique_words)}")Split by Custom Delimiter
tags = "python,django,flask,python,api,django"
unique_tags = set(tags.split(","))
print(unique_tags)Handle Case Sensitivity
Normalize strings before conversion to treat different cases as equal.
text = "Apple APPLE apple aPpLe"
case_sensitive = set(text.split())
print(case_sensitive)
case_insensitive = set(text.lower().split())
print(case_insensitive)Preserve Original Case While Deduplicating
text = "Apple APPLE apple Banana BANANA"
seen = set()
unique = []
for word in text.split():
lower = word.lower()
if lower not in seen:
seen.add(lower)
unique.append(word)
print(unique)Perform Set Operations on String Data
Sets support powerful operations for comparing and combining collections.
text1 = "apple banana cherry"
text2 = "banana cherry date"
set1 = set(text1.split())
set2 = set(text2.split())
common = set1 & set2
print(f"Common: {common}")
all_words = set1 | set2
print(f"All: {all_words}")
only_first = set1 - set2
print(f"Only in first: {only_first}")
exclusive = set1 ^ set2
print(f"Exclusive: {exclusive}")Check Membership Efficiently
Sets provide constant-time membership testing.
allowed_commands = "start stop restart status"
allowed_set = set(allowed_commands.split())
def validate_command(cmd: str) -> bool:
return cmd.lower() in allowed_set
print(validate_command("start")) # True
print(validate_command("delete")) # FalseParse and Deduplicate Structured Data
Handle real-world data with cleaning and deduplication.
raw_emails = """
alice@example.com, ALICE@EXAMPLE.COM,
bob@test.com, charlie@test.com,
BOB@TEST.COM
"""
emails = set(
email.strip().lower()
for email in raw_emails.replace('\n', ',').split(',')
if email.strip()
)
print(emails)Convert Set Back to String
Join set elements to create a deduplicated string.
text = "the quick brown fox jumps over the lazy the dog"
unique_words = set(text.split())
result = ' '.join(unique_words)
print(result)
sorted_result = ' '.join(sorted(unique_words))
print(sorted_result)Output:
quick over dog brown jumps fox the lazy
brown dog fox jumps lazy over quick theQuick Reference
| Goal | Method | Example |
|---|---|---|
| Unique characters | set(s) |
set("hello") → {'h','e','l','o'} |
| Unique words | set(s.split()) |
"a b a" → {'a', 'b'} |
| Case-insensitive | set(s.lower().split()) |
Normalizes case first |
| Count unique | len(set(s)) |
Returns unique count |
| Check membership | x in set(s) |
O(1) lookup |
Conclusion
Use set() for character-level deduplication and set(s.split()) for word-level deduplication. Normalize with lower() when case-insensitive comparison is needed. Sets excel at membership testing and comparing collections with operations like intersection and difference, but remember they do not preserve element order.