python-conversion-tipos

Type Conversion in Python

  • 2 min

In Python, it is possible to convert between data types using built-in functions. Some of the most common conversion functions include:

FunctionDescription
int()Converts a value to an integer
float()Converts a value to a float
str()Converts a value to a string
bool()Converts a value to a boolean

It is important to note that not all conversions are possible. If an invalid conversion is attempted, information loss (or even an error) can 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 generated).

Convert a value to an 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)
Copied!

If the value cannot be converted to a valid integer, an error will be generated.

Convert a value to a 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)
Copied!

If the value cannot be converted to a valid float, an error will be generated.

Convert a value to a 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)
Copied!

Convert a value to a 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)
Copied!