Find Characters in First String that are not Present in Second String
Find Characters in First String and not Present in Second String
To find the characters in a String that are not present in another string, create sets using the given strings, use Difference Operator (-) and pass the two sets as operands to the Difference Operator.
Given two strings: str1
, and str2
; the expression to find the unique characters that are present only in string str1
but not in string str2
is
set(str1) - set(str2)
Example
In the following example, we take two strings in str1
and str2
, and find the characters that are present only in str1
and not in str2
.
Python Program
set1 = set('apple')
set2 = set('banana')
output = set1 - set2
print(output)
Output
{'e', 'l', 'p'}
Summary
In this tutorial of Python Examples, we learned how to find the characters that are present only in the first string, but not in the second string.