Karamzov
Karamzov

Reputation: 403

String comparison in python?

Here i am trying to print unique values in both strings ,

string1 = "wana"
string2 ="sana"
string3 = ""

for wrd in string1 :
    if wrd not in string2:
        string3+=wrd

The above code can compare string1 and return output which is not in string2, i want unique value from both string,here S and W needs to be appenedd to string3 . How to do it without using functions and classes ?

Regards

Upvotes: 2

Views: 221

Answers (3)

Sapan Zaveri
Sapan Zaveri

Reputation: 518

str1 = "sana"
str2 = "wana"
str3=""
for i in range(len(str1)):
    if(str1[i] != str2[i]):
        str3+=str1[i]+str2[i]
print(str3)

Upvotes: 1

Adrian
Adrian

Reputation: 198

Just iterate again, this time over the other string:

string1 = "wana"
string2 ="sana"
string3 = ""

for wrd in string1 :
    if wrd not in string2:
        string3+=wrd

for wrd in string2 :
    if wrd not in string1:
        string3+=wrd

print(string3)

Upvotes: 1

Rakesh
Rakesh

Reputation: 82765

This is one approach. Using set

Ex:

string1 = "wana"
string2 ="sana"

string3 =  "".join(set(string1) ^ set(string2))
print(string3)

Output:

sw

Upvotes: 6

Related Questions