This tutorial explains how to get numbers from a string in Python. It also lists some example codes to further clarify the concept using different approaches.

Numbers from a string can be obtained by simple list comprehension. split() method is used to convert string to a list of characters and isdigit() method is used to check if a digit is found through the iteration.

A basis code example is given as:

temp_string = "Hi my age is 32 years and 250 days12" print(temp_string) numbers = [int(temp)for temp in temp_string.split() if temp.isdigit()] print(numbers)

Output:

Hi my age is 32 years and 250 days12 [32, 250]

However, this code does not identify numbers that come with alphabets.

The re module of Python also provides functions that can search through the string and extract results. The re module provides with the findall() method that returns a list of all the matches. An example code is given below:

import re temp_string = "Hi my age is 32 years and 250.5 days12" print(temp_string) print([float(s) for s in re.findall(r'-?\d+\.?\d*', temp_string)])

Output:

Hi my age is 32 years and 250.5 days12 [32.0, 250.5, 12.0]

The RegEx solution works for negative and positive numbers and overcomes the problem encountered in the List Comprehension approach.

DelftStack articles are written by software geeks like you. If you also would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Python String

  • Count the Occurrence of a Character in a String in Python
  • Compare Strings in Python
  • Extract numbers from string list Python
    report this ad