Click for Python Type Casting (Part 1)
Python Type Casting
Continue the Python type casting tutorial. In the previous tutorial, we learned about implicit and explicit casting in Python. Python has several built-in functions that are used in explicit casting. We already learned about the int() function. Now continue with the rest of the built-in functions.
float() function in Python
The float() function is used to convert a data type into a float data type. We already learned about the float function in implicit casting. Syntax for the float() function:
Syntax: float(value) value = Only one argument is required; we can provide any value that could be converted into a float. |
In the implicit casting, other data types are automatically converted into float data types. For example:
Code:
a = 10
b = 20.0
c = a + b
print(c)
print(type(c))
Output:
30.0
<class 'float'>
Here, a is an int data type, and b is a float data type. Whenever the interpreter does an operation between int and float, int will automatically be converted into float. However, we can do it manually too. For example:
Code:
num1 = '22'
print(type(num1))
num2 = float(num1)
print(type(num2))
print(num2)
Output:
<class 'str'>
<class 'float'>
22.0
Here num1
is a string and we use the float() function to convert num1
into a float data type. However, not every string value can be converted into a float data type. For example:
Code:
text = float('Python')
print(text)
Output:
ValueError: could not convert string to float: 'Python'
So we cannot change every string value into a float data type. Only a numeric string value has the possibility to change into a float data type. We can also convert a mathematical output into a float data type. For example:
Code:
num1 = 10
num2 = 20
print(float(num1+num2))
Output:
30.0
Here the output should be only 30, but we use the float() function so we get the output in the decimal number.
complex() Function in Python
The complex() function is used to convert a data type into a complex data type. Complex numbers are made of two parts: real and imaginary. Syntax for the complex() function:
Syntax: complex (real, imaginary) It took two arguments: real (required) = first argument; we provide a number here; this is the real part of the complex number. So we provide a real number here. The number could be positive, negative, or zero. The default value is zero. imaginary (optional) = second argument; here we provide an imaginary number. The default value is zero. |
For example:
Code:
num1 = '4+5j'
print(type(num1))
num2 = complex(num1)
print(num2)
print(type(num2))
Output:
<class 'str'>
(4+5j)
<class 'complex'>
Here we have converted a string into a complex data type. Here, ‘4+5j’ means 4 is the real part and 5j is the imaginary part of the complex number. If we have only the real part, then:
Code:
num1 = 4
num2 = complex(num1)
print(num2)
Output:
(4+0j)
Here num1 is an integer and we converted this into a complex number. We only provide the real part of the complex number. So we get 0j in the imaginary part. If we didn’t provide any imaginary number, then the default number is zero. Now if we provide both real and imaginary parts:
Code:
num1 = 4
num2 = 5
num3 = complex(num1, num2)
print(num3)
Output:
(4+5j)
If we didn’t provide any real or imaginary number, then:
Code:
num1 = complex()
print(num1)
Output:
0j
If we want only an imaginary part in the output, then:
Code:
num1 = 5
num2 = complex(imag=num1)
print(num2)
Output:
5j
So this is how we can convert other data types into complex data types.
str() function in Python
The str() function is used to convert a data type into a string data type. Syntax for str() function:
Syntax: str(object, encoding, errors) It took three arguments. First is required and others are optional. Object (required): First argument: Here we provide any data type, which we want to convert into a string data type. Encoding (optional): Second argument. Here we provide the encoding method for the object. Default value is UTF-8. UTF means unicode transformation format, and 8 numbers indicate the 8-bit values are used for endcoding. We can change values to UTF-16, UTF-32, etc. Errors (optional): Third argument. If decoding is failed, then how should the error be handled? We set value in this argument for error handling. Default value is 'strict'. |
For example:
Code:
num1 = 15
string_int = str(num1)
print(string_int)
print(type(string_int))
num2 = True
string_bool = str(num2)
print(string_bool)
print(type(string_bool))
num3 = 4+5j
string_complex = str(num3)
print(string_complex)
print(type(string_complex))
Output:
15
<class 'str'>
True
<class 'str'>
(4+5j)
<class 'str'>
Here we changed some different kinds of data types into string data types. In num3
, we have a complex number; we still changed the complex number into a string data type. Complex numbers can only be changed into string data types.
tuple() function in Python
The tuple() function is used to convert a data type into a tuple data type. Syntax for tuple() function:
Syntax: tuple(iterator) Only one argument is required. Iterator (required): Here we provide any iterable object. |
For example:
Code:
data1 = "Python"
tuple_str = tuple(data1)
print(tuple_str)
print(type(tuple_str))
data2 = ['Hello', 'Python', 100]
tuple_list = tuple(data2)
print(tuple_list)
print(type(tuple_list))
Output:
('P', 'y', 't', 'h', 'o', 'n')
<class 'tuple'>
('Hello', 'Python', 100)
<class 'tuple'>
Here we converted a string and a list data type into a tuple data type. If we try to convert a non-iterable object into a tuple data type:
Code:
data1 = 100
tuple_int = tuple(data1)
print(tuple_int)
Output:
TypeError: 'int' object is not iterable
Here we try to convert an integer number into a tuple. But integer data type is a non-iterable object. So we get a TypeError in the output.
list() Function in Python
The list() function is used to convert a data type into a list data type. Syntax for list() function:
Syntax: list(iterable) Only one mandatory argument. Iterator (required): Here we provide any iterable object. |
Code:
data1 = 'Python'
list_str = list(data1)
print(list_str)
print(type(list_str))
data2 = ('Hello', 'Python', 10)
list_tuple = list(data2)
print(list_tuple)
print(type(list_tuple))
Output:
['P', 'y', 't', 'h', 'o', 'n']
<class 'list'>
['Hello', 'Python', 10]
<class 'list'>
So this is how we can convert other data types into list data types.
set() Function in Python
The set() function is used to convert a data type into a set data type. Syntax for set() function:
Syntax: set(iterable) Only one mandatory argument. Iterator (required): Here we provide any iterable object. |
For example:
Code:
data1 = ('This', 'Time')
set_tuple = set(data1)
print(set_tuple)
print(type(set_tuple))
data2 = ['Hello', 'Python']
set_list = set(data2)
print(set_list)
print(type(set_list))
Output:
{'This', 'Time'}
<class 'set'>
{'Hello', 'Python'}
<class 'set'>
So this is how we convert other data types into set data types.
dict() Function in Python
The dict() function is used to create a dictionary object. We can also change another data type into a dictionary data type. For example:
Code:
new_dict = dict(name = 'A', age = 33, place = 'UK')
print(new_dict)
Output:
{'name': 'A', 'age': 33, 'place': 'UK'}
So this is how we can create a dictionary with the help of the dict() function. We can also convert other data types into dictionaries. For example:
Code:
first_tuple = (['Fruit', 'Mango'], ['Number', 1], ['Name', 'A'])
print(type(first_tuple))
first_dict = dict(first_tuple)
print(first_dict)
print(type(first_dict))
Output:
<class 'tuple'>
{'Fruit': 'Mango', 'Number': 1, 'Name': 'A'}
<class 'dict'>
So here we have a tuple and we converted this tuple into a dictionary. Dictionaries always work in key-value pairs. For example:
Code:
name = "Python"
name2 = dict(name)
print(name2)
Output:
ValueError: dictionary update sequence element #0 has length 1; 2 is required
We get a ValueError, because we provide only one value and it is not sufficient to create a dictionary.
frozenset() Function in Python
The frozenset() function is used to convert a mutable data type into an immutable data type. For example:
Code:
new_set = frozenset({'Apple', 'Mango'})
print(new_set)
print(type(new_set))
Output:
frozenset({'Apple', 'Mango'})
<class 'frozenset'>
chr() Function in Python
We can get a unicode number for any character by using the chr() function. Unicode is a system where every character has a unique number. Beside numbers, we can get unicode numbers for punctuation and mathematical symbols. We provide the number in the parameter of chr(). Characters are followed by the ASCII encoding system. The chr() function accepts the unicode value within the range of 0 to 1114111. Syntax for chr() function:
Syntax: chr(num) Only one argument is required. num (required): Here we provide a valid unicode number. |
For example:
Code:
num1 = chr(65)
print(num1)
Output:
A
Here we provide number 65 as argument and we get character A
in the output. So this is how we provide the unicode number and get the character in the output. Another example:
Code:
num1 = chr(83)
print(num1)
Output:
S
The output always comes in a string. It doesn’t matter if we get a letter, number, or any symbol in the output. chr() function always returns a string as output. For example:
Code:
num1 = chr(100)
print(num1)
print(type(num1))
Output:
d
<class 'str'>
So we get 'str'
class in the output.
ord() Function in Python
ord() function is just opposite of chr() function. We provide any character as an argument with the ord() function and we get the unicode value for that character. And because we are writing the character, we have to use quotes. For example:
Code:
num1 = ord('A')
print(num1)
Output:
65
So we get the unicode number for character A. The ord() function represents the int class. For example:
Code:
num1 = ord('P')
print(num1)
print(type(num1))
Output:
80
<class 'int'>
We get the ‘int’ class in the output.
Conclusion
So this is the end of the Python type casting tutorial. These are the basic and most usable converters, which we used in Python programming. There are some other converters too but these are the basic converters required for coding in Python. Casting is very important because most of the time we have to convert a data type into another data type.
End of the Python Type Casting (Part 2) tutorial.
2 thoughts on “Python Type Casting (Part 2): What is Type Casting or Type Conversion in Python?”