Home > OS >  Removing all non-numeric values from a string
Removing all non-numeric values from a string

Time:04-08

The task is to return all numbers in a string, excluding all letters. My current is such as:

def get_digits(cs: str) -> str:
   

    str1 = ''
    for c in cs:
        if c.isdigit():
            a = str1.join(c)

        

    return a

For example, when get_digits("a1b2c3") is entered, the desired output is 123. Currently the returned result is '3'. Any help would be much appreciated. Thank you

CodePudding user response:

Regex is your better option here, if you want to remove all non-digit, you can do something like

>>> cs = "a1b2c3"
>>> re.sub('\D', '', cs)
'123'

But you can do better by extracting directly numbers in a list

>>> cs = "a1b24c3"
>>> re.findall(r'\d ', cs)
['1', '24', '3']

both solutions works, it depends of your use case.

CodePudding user response:

Your code is returning '3' because you are overwriting the 'a' variable each time the iteration of the for loop ends You can just concatenate each result number to the str1 variable:

def get_digits(cs: str) -> str:
       

    str1 = ''
    for c in cs:
        if c.isdigit():
            str1  = c
            # str1  = c it's the same as str1 = str1   c

        

    return str1

This will return your desired output

CodePudding user response:

You can achieve this by using only string related functions, like below:

input_str = "a1b2c3"

numbers = ''.join((ch if ch in '0123456789' else ' ') for ch in input_str)
numbers_list = [int(i) for i in numbers.split()]

print(numbers_list)
  • Related