Convert String to Integer and Vice Versa
Quick Overview
`int("12")` parses, but `int("12.5")` raises `ValueError` rather than truncating. `int(12.5)` does truncate, toward zero, which is why the two look inconsistent.
Deep Dive
1. The Challenge: Type Casting
Write two functions: string_to_int(txt) that converts a numerical string into an integer, and int_to_string(num) that converts an integer into a string.
2. Why It Matters
User inputs (from forms or command line arguments) enter Python as strings. Converting them to numbers is required before doing math operations.
3. The Python Solution
Use built-in int() and str() type casting functions:
def string_to_int(txt):
return int(txt)
def int_to_string(num):
return str(num)
# Testing string to int
print(string_to_int("6"), type(string_to_int("6"))) # Output: 6 <class 'int'>
print(string_to_int("1000")) # Output: 1000
# Testing int to string
print(int_to_string(45), type(int_to_string(45))) # Output: '45' <class 'str'>
4. How Type Casting Operates
Python is strongly typed, meaning it will NOT implicitly convert "5" + 5 (this raises a TypeError). Explicit type casting via int() and str() is required.
5. Common Mistakes
- ValueError on Invalid String: Passing non-numeric text to
int("hello")raises aValueError: invalid literal for int() with base 10. Usetry/exceptblocks when parsing unpredictable user input.
6. Next Steps
Use int() and str() for explicit type casting. Next, let's count words in a sentence!
Next Up in Python Beginner Practice & Core Problem Solving
Return the Sum of Two Numbers
A function with no `return` hands back `None`, so a forgotten one surfaces as a `TypeError` at the call site rather than at the line that actually caused it.
Convert Minutes into Seconds
`minutes * 60` returns an `int` when given an `int`, while `/` always produces a float regardless of the operands. Multiplication preserves the type; division does not.
Calculate the Area of a Triangle
`base * height / 2` always yields a float in Python 3 because `/` never returns an int, even for whole numbers. `//` floors instead, which is almost never what an area wants.