Python: Separate and print the numbers and their position of a given string
29. Numbers and Positions
Write a Python program to separate and print the numbers and their position in a given string.
Sample Solution:
Python Code:
import re
# Input.
text = "The following example creates an ArrayList with a capacity of 50 elements. Four elements are then added to the ArrayList and the ArrayList is trimmed accordingly."
for m in re.finditer("\d+", text):
print(m.group(0))
print("Index position:", m.start())
Sample Output:
50 Index position: 62
Pictorial Presentation:
Flowchart:

For more Practice: Solve these Related Problems:
- Write a Python program to extract all numbers from a string along with their starting positions using regex.
- Write a Python script to find and print each number in a string and its corresponding index.
- Write a Python program to scan a string for digit sequences, and then output each sequence along with its position.
- Write a Python program to search a string for numbers and print a tuple for each containing the number and its start and end indices.
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Python program to find all words starting with 'a' or 'e' in a given string.
Next: Write a Python program to abbreviate 'Road' as 'Rd.' in a given string.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.