w3resource
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!

Flowchart:

Flowchart: Regular Expression - Search some literals strings in a string.

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write Python program to search the numbers (0-9) of length between 1 to 3 in a given string.
Next: Write a Python program to search a literals string in a string and also find the location within the original string where the pattern occurs.

What is the difficulty level of this exercise?



New Content: Composer: Dependency manager for PHP, R Programming