Program to search words in a string using a function

In this python function program, we will search words in a string using a function.

What is Function?
It is a block of code that executes when it is called.
To create a function use def keyword.

Steps to solve the program
  1. Create a function search.
  2. Use the def keyword to define the function.
  3. Take a string and a word as input through the user.
  4. Create a count variable and assign its value equal to 0.
  5. Use a for loop to iterate over the words in the string after splitting it using split(” “).
  6. Use an if statement to check whether the word is in the string or not.
  7. If yes then add 1 to the count variable.
  8. Based on the value of the count variable and using an if-else statement determine whether the word is in the string or not.
  9. Print the respective output.
  10. Call the function to get the output.
				
					def search():
    str1 = input("Enter string: ")
    str2 = input("Enter word: ")
    count = 0
    for word in str1.split(" "):
        if word == str2:
            count += 1
    if count > 0:
        print(f"{str2} is in {str1}")
    else:
        print(f"{str2} is not in {str1}") 
search()
				
			

Output :

				
					Enter string: python programming
Enter word: python
python is in python programming
				
			

Related Articles

add two Binary numbers.

get the length of the last word in a string.

Leave a Comment