41. Problem to check if an element in a set is a substring of a string

In this Python set program, we will check whether an element in a set is a substring of a string or not with the help of the below-given steps.

What is set?
Sets are used to store multiple items in a single variable.
The set is one of 4 built-in data types in Python used to store collections of data.
It is an unordered collection data type that is iterable, mutable and has no duplicate elements.

Element in a set is a substring of a string:

Steps to solve the program

1. Create a string and a set containing words.
2. Create a count variable and assign its value equal to 0.
3. Use a for loop to iterate over words in the set.
4. Use an if statement to check whether the word is in string or not.
5. If yes then add 1 to the count variable.
6. If the value of the count variable is greater than 0 then an element in a set is a substring of a string, else not.
7. Print the respective output.

				
					String = "Learning python is fun"
Set = {"fun","python"}
count = 0
print("String: ",String)
print("Set: ",Set)
for word in Set:
    if word in String:
        count += 1
if count > 0:
    print("An element in a set is a substring of a given string")
else:
    print("An element in a set is not a substring of a given string")
				
			

Output :

				
					String:  Learning python is fun
Set:  {'fun', 'python'}
An element in a set is a substring of a given string
				
			

Related Articles

find the intersection between multiple sets.

Leave a Comment