Create util module with first function
This commit is contained in:
1 parent
793464ff81
commit
e8c94e7f7b
2 files changed
+26
No files matched your search
Whitespace-only changes.
@@ -0,0 +1,26 @@
|
|||||||
|
import re
|
||||||
|
|
||||||
|
|
||||||
|
class InvalidStringException(Exception):
|
||||||
|
"""Raised when a string cannot be converted to an integer."""
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def convert_string_to_integer(data: str) -> int | Exception:
|
||||||
|
"""
|
||||||
|
Converts a string to an integer value.
|
||||||
|
:param data: A string containing an integer or float value to convert
|
||||||
|
:return: The converted integer value or exception object
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
>>> safe_int_from_string("4")
|
||||||
|
>>> safe_int_from_string("3.0")
|
||||||
|
"""
|
||||||
|
|
||||||
|
try:
|
||||||
|
if '.' in data:
|
||||||
|
return int(float(data))
|
||||||
|
else:
|
||||||
|
return int(data)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise InvalidStringException("The string could not be converted to an integer.") from exc
|
||||||
Reference in new issue
Block a user