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
- Create a function search.
- Use the def keyword to define the function.
- Take a string and a word as input through the user.
- Create a count variable and assign its value equal to 0.
- Use a for loop to iterate over the words in the string after splitting it using split(” “).
- Use an if statement to check whether the word is in the string or not.
- If yes then add 1 to the count variable.
- Based on the value of the count variable and using an if-else statement determine whether the word is in the string or not.
- Print the respective output.
- 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
Python function program to get the length of the last word in a string.
Python function program to get a valid mobile number.
Python function program to convert an integer to its word format.
Python function program to get all permutations from a string.
Python function program to add two numbers.
Python function program to print the input string 10 times.