Safe String to Integer

Easy ⏱ 8 min 89% acceptance ★★★★☆ 4.3
Write a function safe_int(text) that converts a string text to an int and returns it. If the conversion fails (the string is not a valid integer), return None instead of raising an error.

Examples

Example 1
Input
safe_int("42")
Output
42
Explanation

Valid integer string.

Example 2
Input
safe_int("abc")
Output
None
Explanation

"abc" cannot become an int.

Constraints

  • `text` is always a string.
  • Whitespace-only or empty strings should also return None.

Topics

Variables & Data Typestype casting

Companies

FlipkartZomatoWipro

Hints

Hint 1

Wrap `int(text)` in a try/except ValueError.

Hint 2

Remember int() already strips surrounding whitespace on valid numbers.

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