In Python, it is possible to convert between data types using built-in functions. Some of the most common conversion functions include:
Function | Description |
---|---|
int() | Converts a value to integer |
float() | Converts a value to float |
str() | Converts a value to string |
bool() | Converts a value to boolean |
It is important to note that not all conversions are possible. In the case of making an invalid conversion, information loss (or even an error) may occur.
For example,
- When converting a float to an integer, the decimal part will be truncated
- When converting a string to a number, the text value must be a valid number (otherwise, an error will be raised)
Convert a value to integer
The int()
function is used to convert a value to an integer.
# Conversion from float to integer
float_value = 3.14
integer = int(float_value)
# Conversion from string to integer
string = "25"
integer = int(string)
# Conversion from boolean to integer
boolean = True
integer = int(boolean)
If the value cannot be converted to a valid integer, an error will be raised.
Convert a value to float
The float()
function is used to convert a value to a floating-point number.
# Conversion from integer to float
integer = 10
float_value = float(integer)
# Conversion from string to float
string = "3.14"
float_value = float(string)
# Conversion from boolean to float
boolean = True
float_value = float(boolean)
If the value cannot be converted to a valid float, an error will be raised.
Convert a value to string
The str()
function is used to convert a value to a string. This function can convert values of any type to a string representation.
# Conversion from integer to string
integer = 10
string = str(integer)
# Conversion from float to string
float_value = 3.14
string = str(float_value)
# Conversion from boolean to string
boolean = True
string = str(boolean)
Convert a value to boolean
The bool()
function is used to convert a value to a boolean value. In Python, any value can be converted to a boolean, and the result can be True
or False
.
# Conversion from integer to boolean
integer = 0
boolean = bool(integer)
# Conversion from string to boolean
string = "True"
boolean = bool(string)
# Conversion from float to boolean
float_value = 0.0
boolean = bool(float_value)