简体   繁体   English

在python中查找并打印字符串中的所有数字

[英]find and print all numbers in a string in python

I need to make a code with a FOR loop that will find all numbers in a string and then print out all the numbers. 我需要使用FOR循环编写代码,该代码将查找字符串中的所有数字,然后打印出所有数字。 So far I have only been able to get the code to print out the first number that is found can you help me pleas? 到目前为止,我只能获取代码以打印出找到的第一个数字,您能帮我请个忙吗?

here is my code: 这是我的代码:

def allNumbers(string):
 for numbers in string:
    if numbers.isdigit():
        return numbers

When the program is run it should look something like this: 当程序运行时,它应如下所示:

>>> allNumbers("H3llO, H0W 4R3 y0U")
'300430'
>>> allNumbers("Good morning.")
''

'' ''

The whole thing could be replaced by a generator expression: 整个事情可以用一个生成器表达式代替:

def allNumbers(string):
    return ''.join(x for x in string if x.isdigit())

Instead of returning the number from your function, just insert it into a list. 无需从函数中返回数字,只需将其插入列表即可。

def allNumbers(string, container=None):
  if not container:
    container = []
  for item in string:
    if item.isdigit():
      container.append(item)
  return container

A better solution: 更好的解决方案:

def allNumbers(orig_str):
  return ''.join(filter(orig_str, str.isdigit))

Yeah it was lame I could think of oneliners only after @Daniels answer :P 是的,只有在@Daniels回答:P之后,我才能想到oneliners。

You can use a list. 您可以使用列表。 And then return it as your desired output. 然后将其作为所需的输出返回。

def allNumbers(string):
    l = []
    for numbers in string:
        if numbers.isdigit():
            l.append(numbers)
    return ''.join(l)

If I am not mistaken, you have asked for whole numbers, not for each digit in the string. 如果我没记错的话,您要的是整数,而不是字符串中的每个数字。 If that is the case, this gives you all the occurrences of separate integer numbers in the string: 如果是这种情况,这将使您在字符串中出现所有单独的整数:

import re
def allNumbers(string):
    regex = re.compile(r'\d+')
    return regex.findall(string)

For example: 例如:

s = "123 sun 321 moon 34"
for num in allNumbers(s):
    print num

outputs: 输出:

123
321
34

NB: the output is a list of strings. 注意:输出是字符串列表。 Cast each element to an integer if you need a number. 如果需要数字,则将每个元素强制转换为整数。

If the input string contains floats (eg 30.21), then their integer and decimal parts are interpreted as distinct integers (30 and 21). 如果输入字符串包含浮点数(例如30.21),则它们的整数和小数部分将解释为不同的整数(30和21)。

If there are no matches, the output is an empty list [] 如果没有匹配项,则输出为空列表[]

#!/usr/bin/python
# -*- coding: utf-8 -*-

s="H3ll0, H0W 4R3 y0U"
result=''
for char in s:
    try:
        number=int(char)
        print number
        result=result+char
    except:
        pass

print 'Result:', result

Output 输出量

3
0
0
4
3
0
Result: 300430

Solution that will work with digits > 9 and doesn't use regular expressions: 适用于数字> 9且不使用正则表达式的解决方案:

def allnumbers(s):
    i = 0
    end = len(s)
    numbers = []
    while i < end:
        if s[i].isdigit():
            number = ''
            while i < end and s[i].isdigit():
                number += s[i]
                i += 1
            numbers.append(int(number))
        else:
            i += 1
    return numbers

This is an other way to do it: 这是另一种方法:

>>> a = 'ad56k34kl56'
>>> x = [i for i in a if i.isdigit()]
>>> ','.join(x)

Output: 输出:

'5,6,3,4,5,6'

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

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