 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
# 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
# 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.
Advertisements
 