简体   繁体   中英

Finding Digits in a String

I'm very new to python and am having trouble with the following bit of code. The aim is to create a function that prints all the integers within a string.

def get_digits(str1):
   for i in str1:
      if i.isdigit():
        return i

However it is only returning the first integer in the string, and I am unsure on how to get it to print all of them.

My apologies if the question is stupid, I have looked around for a while on this site and others and haven't been able to work it out.

Condensed down into a list comprehension

def get_digits(strval):
    return [i for i in strval if i.isdigit()]

print get_digits('432jfsd5fs')
print ''.join(get_digits('432jfsd5fs'))

Returns

['4', '3', '2', '5']
4325
>>> def print_digits(str1):
...    for i in str1:
...       if i.isdigit():
...           print i
... 
>>> print_digits("a12b3")
1
2
3

print prints things. return sends the answer back to whatever ran the function. i guess you are confusing the two because if you run a function within python it prints whatever is returned. but that is only because python is trying to be helpful and show you the result; it's not how you normally print things.

if you really want return the digits, and print them elsewhere, then one way to do it is build a list of results:

>>> def get_digits(str1):
...    results = []
...    for i in str1:
...       if i.isdigit():
...          results.append(i)
...    return results
... 
>>> print(get_digits("a12b3"))
['1', '2', '3']

Whenever you return from a function, the function stops executing. I would recommend a generator here, which allows you to return an iterable from a function without writing much code.

This question smacks of homework, so I'm not going to give the full answer, but I would recommend looking at this StackOverflow answer for a great explanation of generators and the yield keyword.

You can loop through the digits and return a list of them, like this:

def get_digits(str1):
   digits = [] # define new list
   for i in str1:
      if i.isdigit():
        digitis.append(i) # i is a digit, append to list
   return digits # return the list of digits

Your function quits after it finds the first digit. In order for it to return all the digits, collect the results in a list.

def get_digits(str1):
   digits = []
   for i in str1:
      if i.isdigit():
        digits.append(i)
   return digits

You can also simplify your function, by using a list comprehension :

def get_digits(str1):
   return [d for d in str1 if d.isdigit()]

If you just want to print the results and not return them, replace return i with print i in your original function.

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

Simple explanation:

# your code
def get_digits(str1):
   for i in str1:
      if i.isdigit():
        return i

when a function meets return i , it stops its further execution, and return the value.


Since others has explained in detail, I'll just put more solutions for reference:

#1. Using generator
def get_digits_generator(str1):
    for i in str1:
       if i.isdigit():
           yield i

#2. Returning a list of digits
def get_digits_list(str1):
    list_of_digits = []
    for i in str1:
       if i.isdigit():
           list_of_digits.append(i)
    return list_of_digits

#3. List comprehension
str1 = "asdbh12njasdo29ns"
list_of_digits = [character for character in str1 if character.isdigit()]
import re
re.findall('\d', str1)
a=""
def get_digits(str1):
   for i in str1:
      if i.isdigit():
        a=a&i
   return a

try it like this. Because you return while you find the first digital.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM