w3resource

Python: Search a literals string in a string and also find the location where the pattern occurs


20. Literal String with Position

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:

Python: Regular Expression - Search a literals string in a string and also find the location where the pattern occurs.

Flowchart:

Flowchart: Regular Expression - Search a literals string in a string and also find the location where the pattern occurs.

For more Practice: Solve these Related Problems:

  • Write a Python program to search for a literal string in a text and print its first occurrence index.
  • Write a Python script to locate a specified literal substring in a string and display its start and end positions.
  • Write a Python program to find all occurrences of a literal string within a text and then print each position where it occurs.
  • Write a Python program to search for a given literal string in a text and return the substring along with its index.

Go to:


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.

Python Code Editor:

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

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.