Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Problem No 15

Convert String to Integer

Medium

15 minute session

Summary

Convert a numeric string into an integer, handling optional whitespace and sign characters.

Problem statement

Create a function that accepts a string representing an integer and returns its integer value. The input string may include leading or trailing whitespace and an optional '+' or '-' sign. You may assume the string represents a valid integer (no letters or decimal points). Do not print; return the integer.

Task

Write a function that converts a string containing an integer into a Python int.

Examples

Simple positive number

Input

str_to_int('42')

Output

42

Explanation

The string '42' converts to the integer 42.

Whitespace and negative number

Input

str_to_int(' -7 ')

Output

-7

Explanation

Leading/trailing whitespace is ignored and the sign is preserved.

Input format

A single string argument is passed to str_to_int(s).

Output format

Return the integer value represented by the string.

Constraints

Input strings are guaranteed to represent valid integers. Use int() conversion and return the result.

Samples

Sample input 0

str_to_int('0')

Sample output 0

0

Explanation 0

The string '0' converts to integer 0.

Code editor
Loading editor…

AI assistant

Ask me anything!

Need help? I can explain the core idea behind this problem, review your current code, and give targeted hints. Use “Teach Theory” for the concept, “Get AI hint” for a quick scaffold nudge, or ask a specific question below.

Chat history is temporary and will not be saved.

04:59 AM

Free preview includes 1 Teach Theory response and 1 AI hint per unlocked preview lesson.