Python Data Type Conversion
During programming, we often need to convert between different data types. For example, getting numbers from user input (which is always a string), or concatenating numbers into text. Python provides a series of built-in functions to perform these type conversion operations.
This type of type conversion explicitly specified by programmers is called explicit type conversion.
Common Conversion Functions
Converting to Integer: int()
The int() function can create an integer from a float or numeric string.
-
Converting from a Float: The decimal part is directly truncated, not rounded.
-
Converting from a String: The string must contain only integer numbers.
Converting to Float: float()
The float() function can create a float from an integer or numeric string.
Converting to String: str()
The str() function can convert almost any object of any other data type to its string representation.
Converting to Sequence Types
Converting to List: list()
The list() function can convert an iterable (such as a string, tuple, or set) into a list.
Converting to Tuple: tuple()
The tuple() function can convert an iterable into a tuple.
Converting to Set: set()
The set() function can convert an iterable into a set. Note that sets will automatically remove duplicate elements.
Implicit Type Conversion
Besides explicit conversion, Python also automatically performs implicit type conversion in certain situations. This typically happens in operations with different numeric types; Python will "promote" lower-precision types to higher-precision types to avoid data loss.