0

How to write a Python function that take one String argument and return following three type of output types depending on input value

def parseValue(v):
...

For example:

"123.45" -> parseValue("123.45") -> 123.45 (float)

"12345" -> parseValue("12345") -> 12345 (int)

"-23" -> parseValue("-23") -> -23 (int)

"Florida" -> parseValue("Florida") -> Florida (String and kept the input unchanged)

"0.12" -> parseValue("0.12") -> 0.12 (float)

"0010" -> parseValue("0010") -> "0010" keep it as string since this could be a code that require leading zeros

TW2021
  • 21
  • 4
  • Does this answer your question? [How do I parse a string to a float or int?](https://stackoverflow.com/questions/379906/how-do-i-parse-a-string-to-a-float-or-int) – Random Davis Sep 13 '21 at 19:31

1 Answers1

0
from typing import Union

def parse_value(val: str) -> Union[float, int, str]:
  try:
    res = float(val)
    if res.is_integer():
      res = int(res)
    if not val.startswith('0') or '.' in val:
      return res
  except ValueError:
    pass
  return val
>>> parse_value('123.45')
123.45
>>> parse_value('12345')
12345
>>> parse_value('-23')
-23
>>> parse_value('Florida')
'Florida'
>>> parse_value('0.12')
0.12
>>> parse_value('0010')
'0010'
>>> parse_value('0000')
'0000'
Adam Bright
  • 126
  • 1
  • 11
  • Is this is a valid syntax in Python3? `def parse_value(val: str) -> float | int | str:` I am getting this error `TypeError: unsupported operand type(s) for |: 'type' and 'type' ` Python version I am using is: Python 3.9.6 – TW2021 Sep 20 '21 at 01:27
  • @TW2021, i'm sorry for this, i'm using 3.10.0rc2 (release candidate version), and already got used to these type definitions. For 3.9.6 it will be `typing.Union[float, int, str]` – Adam Bright Sep 22 '21 at 10:02
  • Adam thanks for the sample function, it work great except for this user case ` parse_value('0000')` return int 0, I would expect it to be return string '0000'. – TW2021 Sep 23 '21 at 13:34
  • @TW2021 , updated to suit your expectations – Adam Bright Sep 23 '21 at 14:21
  • Adam, this is working great, thank you! – TW2021 Sep 24 '21 at 14:30