In Python, you can use the following built-in functions to convert a string to an integer and a string to a float:
-
Convert String to Integer:
- Use the
int()function. - Example:
string_number = "42" integer_value = int(string_number) # Converts to integer 42
- Use the
-
Convert String to Float:
- Use the
float()function. - Example:
string_number = "3.14" float_value = float(string_number) # Converts to float 3.14
- Use the
These functions will raise a ValueError if the string cannot be converted to the respective type, so it's good practice to handle exceptions when using them. If you want to explore more about type conversion, consider checking out relevant labs on LabEx!
