0

input:

I am 52 years old. The 48a24 is an example.

output:

52, 48, 24

this is my code:

string=''
string=input()

def finddigits(string):
    digits=''
    string.split()
    for i in string:
        if i.isdigit():
            digits += i
    return digits

res = [int(i) for i in string.split() if i.isdigit()]
print(finddigits(string))

but my output is not same with what i want

shabnam
  • 1
  • 2
  • 1
    What have you tried, and what exactly is the problem with it? – jonrsharpe Apr 26 '20 at 19:08
  • @shabnam Welcome to Stackoverflow. I think your question is definitely something that a new user would find challenging, however you should be a little sensitive to the fact that people don't like answering ["homework" questions](https://softwareengineering.meta.stackexchange.com/questions/6166/open-letter-to-students-with-homework-problems) over here. A good question would have a better title and would detail out where exactly you were stuck and needed help with. – Raunak Thomas Apr 26 '20 at 19:22
  • sorry if my question bothering you. – shabnam Apr 26 '20 at 19:29

2 Answers2

0

You could use regular expressions to do this.

There is a very similar question here: Looping through python regex matches

You would just need a slightly different reg expression than the one in the answer from above.

A regex string: ([0-9]+) would give you the answer you want.

Examining the regex above:

  • The parenthesis () are for capturing a group, this is the a piece of the input that you want as an output.
  • The square brackets [] is a regex class.
  • The 0-9 means any number between 0 and 9.
  • The + after the [] means 1 or more class matches.

So in this case [0-9] means match any single digit number. [0-9]+ match any number, and any digit after that.

You can test your regular expressions on this website: https://regex101.com/


Just give me the code:

import re;

s = "I am 52 years old. The 48a24 is an example"
pattern = re.compile(r'([0-9]+)');

for group in re.findall(pattern, s):
    print(group)

Gives output:

52
48
24
Zack
  • 101
  • 4
  • can you please check my code and tell me how i fix the output – shabnam Apr 26 '20 at 19:31
  • I think the issue is that you just add digits and never 'reset' the digits after a non-digit character is reached. I.e.: if i is not a digit start a new number/put a comma in your string. – Zack Apr 26 '20 at 19:35
0

your string.split() is list of words from input string. in your ex I am 52 years old. The 48a24 is an example, only '52' is valid digit and evaluates True for isdigit(). 'some-string'.isdigit() evaluates true when some-string is does not contain any alphabet or special charecters.