• Initialize two strings and an empty string.
  • Iterate over the first string">

    Python - Intersection of two String



    In this article, we are going to learn how to intersect two strings in different ways.

    Follow the below the steps to solve the problem.

    • Initialize two strings and an empty string.
    • Iterate over the first string and add the current character to the new string if it presents in the second string as well and not present in new string already.
    • Print the result.

    Example

     Live Demo

    # initializing the string
    string_1 = 'tutorialspoint'
    string_2 = 'tut'
    
    result = ''
    
    # finding the common chars from both strings
    for char in string_1:
       if char in string_2 and not char in result:
          result += char
    
    # printing the result
    print(result)

    If you run the above code, then you will get the following result.

    Output

    tu
    

    We'll use the set to intersect two strings. Follow the below steps.

    • Convert two strings into sets.
    • Intersect two sets using intersection method.
    • Convert the result to string using join method.
    • Print the result.

    Example

     Live Demo

    # initializing the string
    string_1 = 'tutorialspoint'
    string_2 = 'tut'
    
    # intersection
    result = set(string_1).intersection(string_2)
    
    # converting to string
    result_str = ''.join(result)
    
    # printing the result
    print(result_str)

    If you run the above code, then you will get the following result.

    Output

    ut
    

    Conclusion

    If you have any queries in the article, mention them in the comment section.

    Kickstart Your Career

    Get certified by completing the course

    Get Started
    Advertisements