Reputation: 53
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
(149) (2)
Upvotes: 0
Views: 75
Reputation: 6156
IIUC here is a simple one-liner to solve that, it will return a list of the values (including the comma):
def get_digits(s):
return [data.split(':')[1] for data in s.split(';') if ':' in data]
print(get_digits(s="cycling;time:1,49;distance:2"))
# Output:
# ['1,49', '2']
Expanded it looks like this:
def get_digits(s):
answer = []
# iterate over the split string
for data in s.split(';'):
# check if semicolon is in that string so
# that when splitting there is a second value
if ':' in data:
# append the second item when splitting by colon
answer.append(data.split(':')[1])
return answer
Useful:
Upvotes: 1
Reputation: 3186
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']
Upvotes: 0
Reputation: 1
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))
Upvotes: 0