Data Type Conversions
Data Type Conversions
Here’s a comprehensive overview of data type conversions in Python, covering both implicit and explicit conversions.
Implicit Type Conversion
Python automatically converts one data type to another without user intervention. This usually happens when you mix different data types in an operation.
Examples:
Integer to Float
x = 10 y = 10.5 z = x + y print(z) # Output: 20.5 print(type(z)) # Output: <class 'float'>Integer to Complex
x = 10 y = 2 + 3j z = x + y print(z) # Output: (12+3j) print(type(z)) # Output: <class 'complex'>
Explicit Type Conversion
This requires the user to manually convert one data type to another using built-in functions.
Common Conversions:
String to Integer
s = "100" num = int(s) print(num) # Output: 100 print(type(num)) # Output: <class 'int'>Integer to Float
i = 10 f = float(i) print(f) # Output: 10.0 print(type(f)) # Output: <class 'float'>String to Float
s = "10.5" f = float(s) print(f) # Output: 10.5 print(type(f)) # Output: <class 'float'>Integer to String
i = 10 s = str(i) print(s) # Output: "10" print(type(s)) # Output: <class 'str'>Character to Integer (ASCII)
c = 'A' ascii_val = ord(c) print(ascii_val) # Output: 65 print(type(ascii_val)) # Output: <class 'int'>Integer to Hexadecimal String
i = 255 hex_val = hex(i) print(hex_val) # Output: "0xff" print(type(hex_val)) # Output: <class 'str'>Integer to Octal String
i = 10 oct_val = oct(i) print(oct_val) # Output: "0o12" print(type(oct_val)) # Output: <class 'str'>Float to Integer
f = 10.5 i = int(f) print(i) # Output: 10 print(type(i)) # Output: <class 'int'>Boolean to Integer
b = True i = int(b) print(i) # Output: 1 print(type(i)) # Output: <class 'int'>Integer to Boolean
i = 0 b = bool(i) print(b) # Output: False print(type(b)) # Output: <class 'bool'>
Comments
Post a Comment