Converting Strings to Numbers and Vice Versa
Python provides built-in functions to seamlessly convert between strings and numeric data types (integers and floating-point numbers).
Converting Strings to Numbers
·
int() function: Converts a string representing an integer to an integer value.
Python
string_number = "42"integer_value = int(string_number)print(integer_value) # Output: 42·
float() function: Converts a string representing a floating-point number to a float
value.
Python
string_number = "3.14"float_value = float(string_number)print(float_value) # Output: 3.14Note:
The string must represent a valid number for successful conversion. Otherwise,
a ValueError will be raised.
Converting Numbers to Strings
·
str() function: Converts a number to a string.
Python
number = 42string_value = str(number)print(string_value) # Output: "42"Key Points
·
The int(), float(), and str() functions are essential for
type conversions.
· Ensure the string representation is valid for the desired numeric type.
· Use these conversions when you need to perform arithmetic operations on strings or display numbers as text.
Example:
Python
user_input = input("Enter a number: ") # Input is always a stringnumber = int(user_input)result = number * 2print("Double the number:", result)