easy +10 pts

Safe int parser

Write a parser that returns a default for invalid integers instead of raising.

Write a function `safe_parse_int(text, default=0)` that attempts to parse `text` as an integer. If `text` is a string that represents a valid integer (optionally preceded by a `+` or `-` sign, followed by one or more digits, with no other characters, no spaces, and no decimal point), return the integer value. If parsing fails (e.g., `text` is None, empty, has leading/trailing spaces, contains letters, or is a float), return `default` instead. The function must never raise an exception for any input type.

Constraints

The input `text` can be any type. If it is a string, it must follow the standard integer format: optional leading `+` or `-`, followed by one or more digits, with no whitespace. The `default` parameter is an integer. The function should handle extremely large integers without overflow (Python ints are arbitrary precision). The time complexity is O(n) where n is the length of the string.

Example

>>> safe_parse_int("123")
123
>>> safe_parse_int("-42")
-42
>>> safe_parse_int("3.14")
0
>>> safe_parse_int("  7")
0
>>> safe_parse_int("abc", -1)
-1
>>> safe_parse_int("100", 999)
100
10 points ~10 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Consider using `int(text)` inside a try/except block, but also handle cases like `int(None)` which raises TypeError.
Remember that `int()` returns an exception for strings with leading/trailing spaces, empty strings, and floats.
The `default` parameter should be returned on any exception, but also for types that are not parseable, e.g., `safe_parse_int(None)` should return `default`.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.