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

Live Demo

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.

Updated on: 12-Mar-2021

211 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements