Given a statement(string), the task is to check if that string contains any word which contains ‘a’ in it then print that word otherwise print no any word containing ‘a’ in the inputed string.
Examples :
Input: "W3Colleges provides excellent tutorials" Output: tutorials Input: "Python is fun" Output: no any word containing 'a' in the inputed string Input: "This is a great opportunity" Output: a great
Approach :
Firstly we have to make a regular expression (regex) object that matches a word which contains ‘a’ then we have to pass a string in the findall method. The findall method returns the list of the matched strings. When we got this list we have to loop through it and print each matched word.
here we use shorthand character class \w.
\w - represent Any letter, numeric digit, or the underscore character. symbol * means zero or more occurrence of the character.
Below is the implementation :
# Python program that matches a word
# containing 'a' in the given string
# import required packages
import re
# function to check if any word in the string
# contains 'a', and print it
def check(string):
# The regular expression \w*a\w* will match text
# that has zero or more letter/numeric digits/underscore characters
# followed by 'a', followed by zero or more letter/numeric digits/underscore characters.
regex = re.compile(r"\w*a\w*")
# The findall() method returns all matching strings
# of the regex pattern in a list.
match_object = regex.findall(string)
# if length of match_object is not equal to zero,
# it means it contains matched strings, otherwise,
# it is an empty list (no matched strings found).
if len(match_object) != 0:
# looping through the list to print every word containing 'a'
for word in match_object:
print(word)
else:
print("no any word containing 'a' in the inputed string")
# Driver Code
if __name__ == '__main__':
# Enter the string
string = "W3Colleges provides excellent tutorials"
# Calling check function
check(string)
Output :
tutorials
