w3resource

Python: Search some literals strings in a string


19. Search Literal Strings

Write a Python program to search for literal strings within 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!

Pictorial Presentation:

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

Flowchart:

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

For more Practice: Solve these Related Problems:

  • Write a Python program to search for the literal strings "cat", "dog", and "mouse" in a paragraph and print the found words.
  • Write a Python script to locate and count occurrences of specific literal strings within a given text.
  • Write a Python program to find literal substrings in a text and then highlight them by surrounding them with asterisks.
  • Write a Python program to check if certain literal words exist in a string and then output their starting indices.

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?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.