Find all the numbers in a string in Python

Description :

we will use regular expressions (regex) to fill the numbers in a string in python.

content:

it provide a powerful way to search, extract, and manipulate text based on patterns. The ‘re’ module in Python allows you to work with regular expressions.By using ‘re . findall()’ function, you can easily find all occurrences of a pattern earlier, ‘r’\d+’ is the regex pattern used to find all consecutive digits in the string

Code:

import re

def findAllNumbersFromString(input_string: str):
    if isinstance(input_string, str):
        if re.findall("\d.*?", input_string):
            res = re.findall("\d.*?", input_string)
            return ''.join(res)
        else:
            return "No Number/int is present in given string"
    else:
        return "Please provide valid String"

print(findAllNumbersFromString("divya123di456d"))
print(findAllNumbersFromString("divya"))
print(findAllNumbersFromString(1234))

Output:

123456
No Number/int is present in given string
Please provide valid String

 

 

 

 

 

 

 

Leave a Comment

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

Scroll to Top