Skip to content
Related Articles

Related Articles

Improve Article

Python | Intersection of two String

  • Last Updated : 27 Nov, 2018

One of the string operations can be computing the intersection of two strings i.e, output the common values that appear in both the strings.

There are various ways in Python, through which we can perform the Intersection of two strings.

Method #1 : Naive Method
Create an empty string and check for new occurrence of character common to both string and appending it. Hence computing the new intersection string. This can be achieved by loops and if/else statements.




# Python3 code to demonstrate 
# string intersection
# using naive method 
  
# initializing strings
test_str1 = 'GeeksforGeeks'
test_str2 = 'Codefreaks'
  
# using naive method to
# get string intersection
res = ""
for i in test_str1:
    if i in test_str2 and not i in res:
        res += i
          
# printing intersection
print ("String intersection is : " + res)

Output :

String intersection is : eksfor

 
Method #2 : Using set() + intersection()



Firstly, both the strings are converted into sets using set() and then intersection is performed using intersection(). Returns the sorted set.




# Python3 code to demonstrate 
# string intersection
# using set() + intersection()
  
# initializing strings
test_str1 = 'GeeksforGeeks'
test_str2 = 'Codefreaks'
  
# using set() + intersection() to
# get string intersection
res = set(test_str1).intersection(test_str2)
          
# printing intersection
print ("String intersection is : " + str(res))

Output :

String intersection is : {'e', 'f', 's', 'o', 'k', 'r'}

 

Method #3 : Using join()

join() performs the task similar to list comprehension in case of lists. This encapsulates whole intersection logic and joins together each element filtered through the intersection logic into one string, hence computing the intersection. It converts the strings into set and then computed & operation on them.




# Python3 code to demonstrate 
# string intersection
# using join()
  
# initializing strings
test_str1 = 'GeeksforGeeks'
test_str2 = 'Codefreaks'
  
# using join() to
# get string intersection
res = ''.join(sorted(set(test_str1) &
         set(test_str2), key = test_str1.index))
          
# printing intersection
print ("String intersection is : " + str(res))

Output :

String intersection is : eksfor

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :