Learn type casting in Python using int() and str() functions to convert data between strings and integers.
Learn how to convert minutes into seconds in Python using arithmetic multiplication and basic unit conversions.
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.
User inputs (from forms or command line arguments) enter Python as strings. Converting them to numbers is required before doing math operations.
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'>
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.
int("hello") raises a ValueError: invalid literal for int() with base 10. Use try/except blocks when parsing unpredictable user input.Use int() and str() for explicit type casting. Next, let's count words in a sentence!