Lesson guide
What this Python exercise practices
Convert String to Integer is a intermediate practice lesson that focuses on strings, formatting, traversal. It is designed to be solved in about 15 minutes with examples, starter code, and test feedback.
Prerequisites
- Python variables
- String values
- Basic indexing
Difficulty and time
- Level
- Intermediate
- Estimated time
- 15 minutes
Related public exercises
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.
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.
Free preview includes 1 Teach Theory response and 1 AI hint per unlocked preview lesson.