Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python - Intersection of two String
String intersection finds the common characters between two strings. Python offers multiple approaches: iterating through characters or using set operations for efficient intersection.
Using Character Iteration
This method iterates through the first string and adds characters that exist in both strings while maintaining order ?
# 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)
tu
Using Set Intersection
Converting strings to sets allows us to use the intersection method for finding common characters ?
# 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)
tu
Using Set Intersection with & Operator
The ampersand operator provides a more concise way to find set intersection ?
string_1 = 'tutorialspoint' string_2 = 'tut' # using & operator for intersection result = set(string_1) & set(string_2) result_str = ''.join(sorted(result)) print(result_str)
tu
Comparison
| Method | Preserves Order | Time Complexity | Best For |
|---|---|---|---|
| Character Iteration | Yes | O(n×m) | Order matters |
| Set Intersection | No | O(n+m) | Efficiency |
| & Operator | No | O(n+m) | Concise syntax |
Conclusion
Use character iteration when order preservation is important. For better performance with large strings, use set intersection methods which offer O(n+m) time complexity.
Advertisements
