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.
To find whether a given string contains a number, convert it to a character array and find whether each character in the array is a digit using the isDigit() method of the Character class.
I would use a regexp: import re threedig = re. compile(r'\b(\d{3})\b') # Regular expression matching three digits. The \b means "word boundary", and (\d{3}) means "three digits", the parenthesis makes it a "group" so the matching text can be found.
What is isdigit in Python? The Python String isdigit() method is a built-in string handling method. If all of the characters in the string are digits, the isdigit() method returns “True.” Otherwise, it returns “False.” This function determines whether the argument contains digits such as 0123456789.
As the others said, you have a semantic problem on your indentation, but you don't have to write such function to do that, a more pythonic way to do that is:
def get_digits(text):
return filter(str.isdigit, text)
On the interpreter:
>>> filter(str.isdigit, "lol123")
'123'
Always test things yourself when people shows 'faster' methods:
from timeit import Timer
def get_digits1(text):
c = ""
for i in text:
if i.isdigit():
c += i
return c
def get_digits2(text):
return filter(str.isdigit, text)
def get_digits3(text):
return ''.join(c for c in text if c.isdigit())
if __name__ == '__main__':
count = 5000000
t = Timer("get_digits1('abcdef123456789ghijklmnopq123456789')", "from __main__ import get_digits1")
print t.timeit(number=count)
t = Timer("get_digits2('abcdef123456789ghijklmnopq123456789')", "from __main__ import get_digits2")
print t.timeit(number=count)
t = Timer("get_digits3('abcdef123456789ghijklmnopq123456789')", "from __main__ import get_digits3")
print t.timeit(number=count)
~# python tit.py
19.990989106 # Your original solution
16.7035926379 # My solution
24.8638381019 # Accepted solution
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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With