Program to print the start and end indices of all the words in the string using Python

Introduction

In this section of python programming our task is to find and print the start and end indices of each word in the given string.

Program to print the start and end indices of all the words in the string

Program

import re


input_srt = input("Enter the string : ")


output = [(i.start(), i.end() - 1) for i in re.finditer(r'\S+', input_srt)]


print("Range of each word in the string are : "+ str(output))

Output

Program to print the start and end indices of all the words in the string Output

Explanation

In the above code, we have used regex finditer() function to find the words in the given string and by using loop we have found the start and end of the words. The values are stored as a tuple list and printed by using the print function.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.