How to Extract Numbers From a String on Python

The ability to perform operations on variables is a fundamental skill in computer programming. In particular, it is sometimes necessary to extract numbers from a string variable. In Python you do this with "re," an integrated Python module that provides fundamental operations for modifying Unicode strings and 8-bit strings. In particular, the "findall" function within the "re" module allows you to search a string from left to right and then pull out values that match your criteria.

Instructions

    • 1

      Import the "re" module as follows:

      import re

    • 2

      Follow the "re" importation with the "findall" command:

      re.findall(r"[-+]?\d*\.\d+|\d+", Var)

    • 3

      Replace "Var" with the string variable from which you would like to extract numbers. Suppose you have the variable "pars" and it contains the string literal "Basketball Free Throws: 2 on Wednesday, 8 on Thursday and 3 on Friday." Thus, your code would read:

      pars = "Basketball Freethrows: 2 on Wednesday, 8 on Thursday and 3 on Friday."
      import re
      re.findall(r"[-+]?\d*\.\d+|\d+", pars)

      The solution set for this code is [2, 8, 3].

Related Searches:

References

Comments

Related Ads

Featured