Python extracts all numbers from a string using regular expressions

Document 对象参考手册Python3 Examples

In Python, we can useremodule to handle regular expressions. To extract all numbers from a string, you can usere.findall()function, which can return all substrings matching the regular expression.

Example

import re

# Example string
text = "The price is 45 dollars and 30 cents."

# Use regular expressions to extract all numbers
numbers = re.findall(r'd+', text)

print(numbers)

Code explanation:

  1. import re: Import Python's regular expression module.
  2. text = "The price is 45 dollars and 30 cents.": Define a string containing numbers.
  3. re.findall(r'd+', text): Usere.findall()function to find in the string all substrings that match the regular expressiond+substrings.d+Indicates matching one or more consecutive digits.
  4. print(numbers): Output all the extracted numbers.

Output result:

['45', '30']

Document 对象参考手册Python3 Examples

Other extensions