Language: EN

python-conversion-tipos

Type Conversion in Python

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

  • int(): Converts a value to an integer.

  • float(): Converts a value to a floating point number.

  • 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. In case of an invalid conversion, information loss may occur, or even an error may be generated.

For example, when converting a float to an integer, the decimal part will be truncated. Similarly, when converting a string to a number, the value of the text 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. If the value cannot be converted to a valid integer, an error will be generated.

Examples

# Conversion from float to integer
float_val = 3.14
integer_val = int(float_val)

# Conversion from string to integer
string_val = "25"
integer_val = int(string_val)

# Conversion from boolean to integer
boolean_val = True
integer_val = int(boolean_val)

Convert a value to a float

The float() function is used to convert a value to a floating point number. If the value cannot be converted to a valid float, an error will be generated.

Examples

# Conversion from integer to float
integer_val = 10
float_val = float(integer_val)

# Conversion from string to float
string_val = "3.14"
float_val = float(string_val)

# Conversion from boolean to float
boolean_val = True
float_val = float(boolean_val)

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.

Examples

# Conversion from integer to string
integer_val = 10
string_val = str(integer_val)

# Conversion from float to string
float_val = 3.14
string_val = str(float_val)

# Conversion from boolean to string
boolean_val = True
string_val = str(boolean_val)

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.

Examples

# Conversion from integer to boolean
integer_val = 0
boolean_val = bool(integer_val)

# Conversion from string to boolean
string_val = "True"
boolean_val = bool(string_val)

# Conversion from float to boolean
float_val = 0.0
boolean_val = bool(float_val)