Python | Union Operation in two Strings

One of the string operation can be computing the union of two strings. This can be useful application that can be dealt with. This article deals with computing the same through different ways.

Method 1 : Naive Method
The task of performing string union can be computed by naive method by creating an empty string and checking for new occurrence of character common to both string and not common strings and appending it and hence computing the new union string. This can be achieved by loops and if/else statements.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python 3 code to demonstrate 
# Union Operation in two Strings
# using naive method 
  
# initializing strings
test_str1 = 'GeeksforGeeks'
test_str2 = 'Codefreaks'
  
# Printing initial strings
print ("The original string 1 is : " + test_str1)
print ("The original string 2 is : " + test_str2)
  
# using naive method to
# Union Operation in two Strings
res = ""
temp = test_str1
for i in test_str2:
    if i not in temp:
        test_str1 += i
          
# printing result
print ("The string union is : " + test_str1)

chevron_right


Output :

The original string 1 is : GeeksforGeeks
The original string 2 is : Codefreaks
The string union is : GeeksforGeeksCda

 

Method 2 : Using set() + union()
Set in python usually can perform the task of performing set operations such as set union. This utility of sets can be used to perform this task as well. Firstly, both the strings are converted into sets using set() and then union is performed using union(). Returns the sorted set.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python 3 code to demonstrate 
# Union Operation in two Strings
# using set() + union()
  
# initializing strings
test_str1 = 'GeeksforGeeks'
test_str2 = 'Codefreaks'
  
# Printing initial strings
print ("The original string 1 is : " + test_str1)
print ("The original string 2 is : " + test_str2)
  
# using set() + union() to
# Union Operation in two Strings
res = set(test_str1).union(test_str2)
          
# printing result
print ("The string union is : " + str(res))

chevron_right


Output :

The original string 1 is : GeeksforGeeks
The original string 2 is : Codefreaks
The string union is : {'s', 'G', 'r', 'e', 'o', 'f', 'k', 'C', 'd', 'a'}



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.