Here are examples of how to change data types in Python using type conversion functions:
- From string to integer:
x = "42" result = int(x) # Converts string to integer print(result) # Output: 42
- From float to integer:
y = 3.9 result = int(y) # Converts float to integer (truncates decimal) print(result) # Output: 3
- From string to float:
x = "3.14" result = float(x) # Converts string to float print(result) # Output: 3.14
- From integer to float:
y = 10 result = float(y) # Converts integer to float print(result) # Output: 10.0
- From integer to string:
x = 42 result = str(x) # Converts integer to string print(result) # Output: "42"
- From float to string:
y = 3.14 result = str(y) # Converts float to string print(result) # Output: "3.14"
- From string to list:
x = "hello" result = list(x) # Converts string to list of characters print(result) # Output: ['h', 'e', 'l', 'l', 'o']
- From tuple to list:
y = (1, 2, 3) result = list(y) # Converts tuple to list print(result) # Output: [1, 2, 3]
- From list to tuple:
x = [1, 2, 3] result = tuple(x) # Converts list to tuple print(result) # Output: (1, 2, 3)
- From list to set:
x = [1, 2, 3, 3] result = set(x) # Converts list to set (removes duplicates) print(result) # Output: {1, 2, 3}
- From list of tuples to dictionary:
x = [("name", "Alice"), ("age", 25)] result = dict(x) # Converts list of key-value pairs to dictionary print(result) # Output: {'name': 'Alice', 'age': 25}
- From string to boolean:
x = "" result = bool(x) # Converts empty string to False print(result) # Output: False
- From integer to boolean:
y = 1 result = bool(y) # Converts 1 to True print(result) # Output: True
- From string to bytes:
x = "hello" result = bytes(x, encoding="utf-8") # Converts string to bytes print(result) # Output: b'hello'
- From list to frozenset:
x = [1, 2, 3, 3] result = frozenset(x) # Converts list to immutable set print(result) # Output: frozenset({1, 2, 3})
- From integer to range:
x = 5 result = range(x) # Creates a range from 0 to 4 print(list(result)) # Output: [0, 1, 2, 3, 4]
These examples demonstrate how to convert various types in Python effectively. If you're working with custom objects or non-standard types, you may need additional handling using custom functions or methods.