float()
Convert a string or number to a floating point number.
number = float("123.45") print(number) # Output: 123.45
int()
Convert a string or number to an integer.
number = int("123") print(number) # Output: 123binary_number = int("101", 2) print(binary_number) # Output: 5
bin()
Convert an integer to a binary string.
number = bin(5) print(number) # Output: '0b101'
hex()
Convert an integer to a hexadecimal string.
number = hex(255) print(number) # Output: '0xff'
oct()
Convert an integer to an octal string.
number = oct(8) print(number) # Output: '0o10'
bool()
Converts the given value to a boolean value. Any non-zero number or non-empty object will be converted to `True`.
print(bool(0)) # Output: Falseprint(bool(1)) # Output: Trueprint(bool("")) # Output: Falseprint(bool("Hello")) # Output: True
list()
Convert an iterable object to a list.
my_tuple = (1, 2, 3) my_list = list(my_tuple) print(my_list) # Output: [1, 2, 3]
tuple()
Convert an iterable object to a tuple.
my_list = [1, 2, 3] my_tuple = tuple(my_list) print(my_tuple) # Output: (1, 2, 3)
dict()
Typically used to convert a list of tuples containing key-value pairs into a dictionary.
my_list = [("a", 1), ("b", 2)] my_dict = dict(my_list) print(my_dict) # Output: {'a': 1, 'b': 2}
set()
Convert an iterable object to a collection.
my_list = [1, 2, 2, 3] my_set = set(my_list) print(my_set) # Output: {1, 2, 3}
complex()
Create a plural number.
c = complex(2, 3) print(c) # Output: (2+3j)
bytes()
Convert an iterable sequence of integers or a string (encoding required) to a sequence of bytes.
b = bytes("hello", "utf-8") print(b) # Output: b'hello'
bytearray()
Similar to `bytes()`, but returns a modifiable byte array.
ba = bytearray("hello", "utf-8") ba[0] = ord('H') print(ba) # Output: bytearray(b'Hello')
This is the end of this article about python type conversion functions. For more related python type conversion functions, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!