How to try parse string to int or float in Python using UliEngineering

You can safely try to parse a string to either an integer or float with error handling using the UliEngineering Python library:

try_parse_int_or_float.py
from UliEngineering.Utils.Parser import try_parse_int_or_float

# Try parsing valid strings
result = try_parse_int_or_float("42")
print(f"Parse '42': {result}")

result = try_parse_int_or_float("3.14")
print(f"Parse '3.14': {result}")

# Try parsing invalid string
result = try_parse_int_or_float("invalid")
print(f"Parse 'invalid': {result}")

Example output

try_parse_int_or_float_output.txt
Parse '42': 42
Parse '3.14': 3.14
Parse 'invalid': None

This function returns None if the string cannot be parsed as a number, rather than raising an exception. This is useful when you need to handle potentially invalid user input gracefully without try-except blocks. Unlike parse_int_or_float, this function won’t raise an exception on invalid input.


Check out similar posts by category: Python, Utilities