Python Program that Displays which Letters are in the Two Strings but not in Both

When working with two strings, we often need to find letters that appear in one string but not in both. Python's set operations provide an elegant solution using the symmetric difference operator (^).

A list can store heterogeneous values (integers, strings, floats, etc.). The list() function converts any iterable to a list type.

Python's set data type contains only unique elements. Sets are useful for operations like intersection, difference, union, and symmetric difference.

Syntax

set1 ^ set2  # Symmetric difference - elements in either set, but not both

Example

Below is a demonstration of finding letters present in either string but not in both ?

string1 = "Jane"
string2 = "Kane"
result = list(set(string1) ^ set(string2))

print("The letters in strings but not in both the strings are:")
for letter in result:
    print(letter)
The letters in strings but not in both the strings are:
K
J

How It Works

The symmetric difference operator (^) returns elements that exist in either set but not in both:

string1 = "hello"
string2 = "world"

set1 = set(string1)
set2 = set(string2)

print("Set 1:", set1)
print("Set 2:", set2)
print("Symmetric difference:", set1 ^ set2)
Set 1: {'e', 'h', 'l', 'o'}
Set 2: {'d', 'l', 'o', 'r', 'w'}
Symmetric difference: {'e', 'h', 'r', 'w', 'd'}

Alternative Methods

Method 1: Using difference() method

string1 = "python"
string2 = "java"

set1 = set(string1)
set2 = set(string2)

# Letters in string1 but not string2, plus letters in string2 but not string1
result = set1.difference(set2).union(set2.difference(set1))
print("Unique letters:", sorted(result))
Unique letters: ['j', 'o', 'p', 't', 'v', 'y']

Method 2: Using symmetric_difference() method

string1 = "data"
string2 = "science"

result = set(string1).symmetric_difference(set(string2))
print("Letters not in both:", sorted(result))
Letters not in both: ['c', 'd', 'i', 's', 't']

Comparison

Method Syntax Readability
^ operator set1 ^ set2 Concise
symmetric_difference() set1.symmetric_difference(set2) More explicit
difference() + union() set1.difference(set2).union(set2.difference(set1)) Most verbose

Conclusion

Use the symmetric difference operator (^) to find letters that appear in either string but not both. The symmetric_difference() method provides the same functionality with more explicit syntax.

Updated on: 2026-03-25T17:39:29+05:30

347 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements