Home > Mobile >  How can I seperate all the numbers from a string as indicated?
How can I seperate all the numbers from a string as indicated?

Time:11-05

So I'm gonna write a code for a bigger program but I'm stuck on this issue. The input for my program is going to be a string like this s="cycling;time:1,49;distance:2" and what I want to do let the program return only the numbers in the provided string. I found how to do that as well like this...

def getDigits(s):
    answer = []
    for char in s:
        if char.isdigit():
            answer.append(char)
    return ''.join(answer)

print(getDigits(s="cycling;time:1,49;distance:2"))

However, even though the output prints out 1492 , I want it to print it out seperately.. so basically I want to let my program print out 1,49 seperately from 2 because 1,49 is the cycling time while 2 is the distance (according to the string input itself). What changes to my code should I make?

Edit: my expected output would be like this... the cycling time values and the distance values are gonna be grouped differently

Expected Output:-

(149) (2)

CodePudding user response:

I would have done it like @heijp06 already mentioned it.

def getDigits(s):
  answer = []
  t = '('   s.split(';')[1].split(':')[1]   ')'
  d = '('   s.split(';')[2].split(':')[1]   ')'
  return ''.join((t,d))

CodePudding user response:

Do some minor changes. Split with ";", then loop:

def getDigits(s):
    answer = []
    for char in s.split(";"):
        k = ""
        for split_s in char:
            if split_s.isdigit():
                k  = split_s
        if k:
            answer.append(k)
    return answer


print(getDigits(s="cycling;time:1,49;distance:2"))

Output :

['149', '2']
  • Related