Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Program that Displays which Letters are in the First String but not in the Second
When it is required to display the letters that are present in the first string but not in the second string, we can use Python's set data structure to find the difference between two strings efficiently.
Python's set contains unique elements only and is useful for performing operations such as intersection, difference, union, and symmetric difference.
Using Set Difference
The most efficient approach is to convert both strings to sets and use the difference operator - ?
# Define two strings
first_string = "programming"
second_string = "coding"
# Find letters in first string but not in second
unique_letters = set(first_string) - set(second_string)
print("First string:", first_string)
print("Second string:", second_string)
print("Letters in first string but not in second:")
for letter in sorted(unique_letters):
print(letter)
First string: programming Second string: coding Letters in first string but not in second: a m p r
Alternative Method Using List Comprehension
You can also use list comprehension with membership testing ?
first_string = "python"
second_string = "java"
# Find unique letters using list comprehension
unique_letters = [char for char in set(first_string) if char not in second_string]
print("First string:", first_string)
print("Second string:", second_string)
print("Unique letters:", sorted(unique_letters))
First string: python Second string: java Unique letters: ['h', 'n', 'o', 'p', 't', 'y']
Case-Sensitive vs Case-Insensitive Comparison
By default, the comparison is case-sensitive. For case-insensitive comparison, convert both strings to lowercase ?
first_string = "Hello World"
second_string = "world hello"
# Case-sensitive comparison
case_sensitive = set(first_string) - set(second_string)
print("Case-sensitive difference:", sorted(case_sensitive))
# Case-insensitive comparison
case_insensitive = set(first_string.lower()) - set(second_string.lower())
print("Case-insensitive difference:", sorted(case_insensitive))
Case-sensitive difference: [' ', 'H', 'W'] Case-insensitive difference: []
How It Works
The process involves these steps:
-
set(first_string)creates a set of unique characters from the first string -
set(second_string)creates a set of unique characters from the second string - The
-operator performs set difference, returning characters present in the first set but not in the second - The result can be converted to a list or iterated directly
Conclusion
Using set difference with the - operator is the most efficient way to find letters in the first string but not in the second. This approach automatically handles duplicates and provides O(n) time complexity for the operation.
