Home > Net >  How can I include decimals in my output as well?
How can I include decimals in my output as well?

Time:11-06

So here's a piece of code that returns all numbers within a given string s.

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

However, if the input s = 'hiking;time:106,01;distance:8.29' is provided, for distance:8.29, the code returns 829 without the decimal point. How can I change my code so that if there is a decimal point in a number, the decimal point gets returned as well??

CodePudding user response:

Change to:

if split_s.isdigit() or split_s in ".,":

You probably want to support both decimal point and comma in order to support European locales. If you only want to support decimal point:

if split_s.isdigit() or split_s == ".":

CodePudding user response:

Strictly speaking, @teambob's answer will do the job.

That being said, you have not specified what constraints exist in your input. If there is a possibility for a dot or comma outside the context of a numeric value, that will fail. Consider using regex to extract it.

import re

def getDigits(s):
    return re.findall('[0-9] [\.|\,]?[0-9]*', s)

This code produces ['106,01', '8.29'] for your input.

CodePudding user response:

as said as teambob, did you mean like this

def getDigits(s):
    answer = []
    for char in s.split(";"):
        k = ""
        for split_s in char:
            if split_s.isdigit() or split_s in ".,":
                k  = split_s
        if k:
            answer.append(k)
    return answer
i=getDigits(s = 'hiking;time:106,01;distance:8.29')
print(i)
#output will be
#['106,01', '8.29']

does this worked for you?

CodePudding user response:

Try little pythonic:

>>> s = 'hiking;time:106,01;distance:8.29'
>>> dict(x.split(":") for x in s.split(";")[1:])
{'distance': '8.29', 'time': '106,01'}
  • Related