w3resource

Python: Separate and print the numbers of a given string


27. Extract Numbers

Write a Python program to separate and print the numbers in a given string.

Sample Solution:

Python Code:

import re
# Sample string.
text = "Ten 10, Twenty 20, Thirty 30"
result = re.split("\D+", text)
# Print results.
for element in result:
    print(element)
	

Sample Output:

10                                                                                                            
20                                                                                                            
30

Pictorial Presentation:

Python: Regular Expression -  Separate and print the numbers of a given string.

Flowchart:

Flowchart: Regular Expression - Separate and print the numbers of a given string.

For more Practice: Solve these Related Problems:

  • Write a Python program to extract all numeric substrings from a text and print them as a list of integers.
  • Write a Python script to identify and separate numbers from a mixed string and then sum them.
  • Write a Python program to use regex to extract numbers from a string and then output them sorted in ascending order.
  • Write a Python program to scan a string for digit sequences, convert them to numbers, and then display the largest number found.

Python Code Editor:

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

Previous: Write a Python program to match if two words from a list of words starting with letter 'P'.
Next: Write a Python program to find all words starting with 'a' or 'e' in a given string.

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.