How to Extract Digits from a String in Python

Whether we are dealing with text data or processing user input, extracting digits can be a common task. So we are going to explore a simple method to achieve this task using Python.

  • Step-by-Step Guide:

The only thing we need to do is make a function for the extraction of digits from the string.

  1. Import the re-module: To start, we need to import a Python built-in module called re-module, which provides support for regular expressions.
  2. Define a Function: Then we’ll define a function called extract_digits that takes an input string as its parameter.
  3. Apply Regular Expression: In the function, we’ll use the function re.findall(). This function is used to search for all occurrences of digits within the input string. The regular expression pattern \d matches any digit.
  4. Join the Results: And finally, we’ll join the list of extracted digits into a single string using the function join(). This method will first extract all the digits from the string and then add them to another single string.

 

  • Complete Code:

import re

def extract_digits(input_string):
    return ''.join(re.findall(r'\d', input_string))

input_string = "Hello 123 World 456"
digits = extract_digits(input_string)
print(digits) 

Here our code ends.

  • Output:

Here the code will remove the char of the string as the function call and print the digits in it.

123456

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top