- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Common words among tuple strings in Python
When it is required to find common words among the tuple strings, the 'join' method, the 'set' method, the '&' operator and the 'split' method is used.
The 'join' method can be used to join multiple values based on a specific value,
Python comes with a datatype known as 'set'. This 'set' contains elements that are unique only. The set is useful in performing operations such as intersection, difference, union and symmetric difference.
The 'split' function splits the given data into multiple sections depending on the value on which it needs to be split.
The '&' operator performs multiplication, i.e AND operation.
Below is a demonstration of the same −
Example
my_tuple_1 = ('Hi there', 'Hi Will,', 'Hi ', 'Hi there') print("The tuple is : ") print(my_tuple_1) my_result = ", ".join(sorted(set(my_tuple_1[0].split()) & set(my_tuple_1[1].split()) & set(my_tuple_1[2].split()))) print("Common words among the tuples are : ") print(my_result)
Output
The tuple is : ('Hi there', 'Hi Will,', 'Hi ', 'Hi there') Common words among the tuples are : Hi
Explanation
- A tuple is defined and is displayed on the console.
- The tuples are split based on empty space, using the 'split' method.
- It is then sorted and joined using the 'sorted' and join' methods respectively.
- This is assigned to a value.
- It is displayed on the console.
Advertisements