Python – Type Conversion
Python provides various functions for converting string, ints, floats, boolean to other types.
Converting String to Ints
If we want to convert a string into an int, then we can do this using the int() function. This can be useful when used with the input() function. The input() function always returns a string. For example,
age = int(input('Please enter your age:')) print(type(age)) print(age)
Above code snippet will give us output as below,
Please enter your age: 21 <class 'int'> 21
Converting String, Ints to Floats
As with integers it is possible to convert other types such as an int or a string into a float. This is done using the float() function:
int_value = 1 string_value = '1.5' float_value = float(int_value) print('int value as a float:', float_value) print(type(float_value)) float_value = float(string_value) print('string value as a float:', float_value) print(type(float_value))
Above code snippet will give us output as below,
int value as a float: 1.0 <class 'float'> string value as a float: 1.5 <class 'float'>
Converting Boolean to Integer
The Boolean type is actually a sub type of integer (but with only the values True and False) so it is easy to translate between the two, using the functions int() and bool() to convert from Booleans to Integers and vice versa. For example:
print(int(True)) print(int(False)) print(bool(1)) print(bool(0))
Above code snippet will give us output as below,
1 0 True False
Converting String to Boolean
You can also convert strings into Booleans as long as the strings contain either True or False (and nothing else) using bool() function. For example:
status = bool(input('OK to proceed: ')) print(status) print(type(status))
Above code snippet will give us output as below,
OK to proceed: True True <class 'bool'>
Conclusion
In this article, we saw about various type conversion using int(), float() and bool() function.