Robust Integer Parser

Easy ⏱ 8 min 81% acceptance ★★★★☆ 4.3
Write to_int(text, fallback=0) that converts a string to an integer, returning fallback when the text isn't a valid integer. Surrounding whitespace is fine (int handles it); '12.5' and 'abc' are not.

Examples

Example 1
Input
to_int('  42 ')
Output
42
Explanation

Whitespace is tolerated by int().

Example 2
Input
to_int('12.5', -1)
Output
-1
Explanation

A float string raises ValueError, so the fallback returns.

Constraints

  • Catch ValueError only.
  • Default fallback is 0.

Topics

Exception HandlingValueError

Companies

InfosysCapgemini

Hints

Hint 1

int(text) does the strict parsing for you.

Hint 2

except ValueError: return fallback.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.