How can we subtract a string from another string in Python? Get the difference of two strings

The Python string doesn't have a subtraction operator. If you want to get the difference of strings, here is a simple and understandable way.

x = 'abcd'
y = 'cdefg'

s = ''
t = ''

for i in x:
    if i not in y:
        s += i

for i in y:
    if i not in x:
        t += i

print(s)  # ab
print(t)  # efg

You can iterate all letters in a string using the for statement and check a string contains a letter by the if-in statement. The s is x - y or the difference of x and y. The t is y - x or the difference of y and x.


Powered by Markdown