w3resource logo


Python Exercises

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 a literals string in a string and also find the location within the original string where the pattern occurs.

Sample text :

'The quick brown fox jumps over the lazy dog.'

Searched words :

‘fox’

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))

Python Code Editor:

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))

Improve this sample solution and post your code through Disqus



Join our Question Answer community to learn and share your programming knowledge.

Help the community:

Python: Fizzbuzz

C++: Decimal to binary conversion

JavaScript: Need Help in JavaScript

Python: Help me with this program