简体   繁体   English

在字符串中查找数字

[英]Finding Digits in a String

I'm very new to python and am having trouble with the following bit of code. 我是python的新手,并且在以下代码方面遇到了麻烦。 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. print打印东西。 return sends the answer back to whatever ran the function. return将答案返回给运行该函数的对象。 i guess you are confusing the two because if you run a function within python it prints whatever is returned. 我想您会混淆这两者,因为如果您在python中运行一个函数,它将打印返回的任何内容。 but that is only because python is trying to be helpful and show you the result; 但这仅仅是因为python试图提供帮助并向您显示结果; 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. 这个问题有点家庭作业,因此我将不给出完整答案,但是我建议您查看此StackOverflow答案 ,以获取有关生成器和yield关键字的详细说明。

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. 如果只想打印结果而不返回结果,请在原始功能中将return i替换为print i

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. 当函数满足return i ,它将停止进一步执行,并返回值。


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. 因为您在找到第一个数字的同时返回。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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