Kevvv Kevvv - 6 months ago 10
Python Question

Python - find digits in a string

def get_digits(str1):
c = ""

for i in str1:
if i.isdigit():
c += i
return c


Above is the code that I used and the problem is that it only returns only the first digit of strings. For this, I have to keep both for loop and return statement. Anyone knows how to fix?

Thanks.

Answer

Your indentation is a bit borked (indentation in Python is quite important). Better:

def get_digits(str1):
    c = ""
    for i in str1:
        if i.isdigit():
            c += i
    return c

A shorter and faster solution using generator expressions:

''.join(c for c in my_string if c.isdigit())
Comments