Python: Search a literals string in a string and also find the location where the pattern occurs
Python Regular Expression: Exercise-20 with Solution
Write a Python program to search for a literal string in a string and also find the location within the original string where the pattern occurs.
Sample Solution:
Python Code:
import re
pattern = 'fox'
text = 'The quick brown fox jumps over the lazy dog.'
match = re.search(pattern, text)
s = match.start()
e = match.end()
print('Found "%s" in "%s" from %d to %d ' % \
(match.re.pattern, match.string, s, e))
Sample Output:
Found "fox" in "The quick brown fox jumps over the lazy dog." from 16 to 19
Pictorial Presentation:
Flowchart:
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Python program to search some literals strings in a string.
Next: Write a Python program to find the substrings within a string.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/python-exercises/re/python-re-exercise-20.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics