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.
pythonx = int(3.14) print(x) # Output: 3 y = int(-5.9) print(y) # Output: -5Converting from a String: The string must contain only integer numbers.
pythonage_str = "25" age_int = int(age_str) print(age_int) # Output: 25 # int("25.5") # Raises ValueError because it contains a decimal point # int("hello") # Raises ValueError because it contains non-numeric characters
Converting to Float: float()
The float() function can create a float from an integer or numeric string.
print(float(10)) # Output: 10.0
print(float("123.45")) # Output: 123.45
print(float("-5")) # Output: -5.0
# float("abc") # Raises ValueErrorConverting to String: str()
The str() function can convert almost any object of any other data type to its string representation.
num = 100
pi = 3.14
my_list = [1, 2, 3]
print(str(num)) # Output: '100'
print(str(pi)) # Output: '3.14'
print(str(my_list))# Output: '[1, 2, 3]'
# Common usage: concatenating strings and numbers
message = "My age is " + str(25)
print(message) # Output: My age is 25Converting to Sequence Types
Converting to List: list()
The list() function can convert an iterable (such as a string, tuple, or set) into a list.
my_str = "hello"
print(list(my_str)) # Output: ['h', 'e', 'l', 'l', 'o']
my_tuple = (1, 2, 3)
print(list(my_tuple)) # Output: [1, 2, 3]
my_set = {1, 2, 3}
print(list(my_set)) # Output: [1, 2, 3] (order may vary)Converting to Tuple: tuple()
The tuple() function can convert an iterable into a tuple.
my_list = [1, 2, 3]
print(tuple(my_list)) # Output: (1, 2, 3)Converting to Set: set()
The set() function can convert an iterable into a set. Note that sets will automatically remove duplicate elements.
my_list = [1, 2, 2, 3, 3, 3]
print(set(my_list)) # Output: {1, 2, 3}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.
int_val = 5
float_val = 2.5
result = int_val + float_val # Python automatically converts int_val to float
print(result) # Output: 7.5
print(type(result)) # Output: <class 'float'>