w3resource logo
Python Exercises

Python: Search some literals strings in a string

Python Regular Expression: Exercise-19 with Solution

Write a Python program to search some literals strings in a string.

Sample Solution:-

Python Code:

import re
patterns = [ 'fox', 'dog', 'horse' ]
text = 'The quick brown fox jumps over the lazy dog.'
for pattern in patterns:
    print('Searching for "%s" in "%s" ->' % (pattern, text),)
    if re.search(pattern,  text):
        print('Matched!')
    else:
        print('Not Matched!')
		

Sample Output:

Searching for "fox" in "The quick brown fox jumps over the lazy dog." ->                                      
Matched!                                                                                                      
Searching for "dog" in "The quick brown fox jumps over the lazy dog." ->                                      
Matched!                                                                                                      
Searching for "horse" in "The quick brown fox jumps over the lazy dog." ->                                    
Not Matched!

Python Code Editor:

import re
patterns = [ 'fox', 'dog', 'horse' ]
text = 'The quick brown fox jumps over the lazy dog.'
for pattern in patterns:
    print('Searching for "%s" in "%s" ->' % (pattern, text),)
    if re.search(pattern,  text):
        print('Matched!')
    else:
        print('Not Matched!')

Improve this sample solution and post your code through Disqus