Back to: Python Programming
Type casting is used to specify the type of a variable. Type casting is also the process of converting a variable from one data type to another. Sometimes, you may want to explicitly define the data type of a variable, and type casting comes in handy. As Python is an object-oriented programming (OOP) language, it has built-in classes to define the data type of variables. You can use the constructor functions of these classes for type casting, which can help you convert a variable from one data type to another.
Let’s look at these functions with examples:
1. str() function
This function is used to create a string. If we use this on an integer or float value, that will also be converted to a string
Example 1:
Suppose we want to create a variable S which will be a string:
S = str("This is a String")
print(S)
print(type(S))
Output:
This is a String
<class 'str'>
So, here str() function is used to construct a string.
Similarly,
Example 2:
strg = str(2)
print(strg )
print(type(strg))
Output:
2
<class 'str'>
Here, str(2) creating a string like : ‘2’, as you can see the class of strg is string.
Example 3:
x = str(3.2)
print(x)
print(type(x))
Output:
3.2
<class 'str'>
1. int() function
This function is used to create an integer value.
Example:
a = int(1)
print(a)
Output:
1
If we use this function on float value, everything after the point will be eliminated.
Example:
b = int(6.99999)
print(b)
Output:
6
If we want to apply int() function on string value, the string need to be a string of numbers.
Example:
c = int('3')
d = int('30000000')
print(c)
print(d)
Output:
3
30000000
3. float() function
This function is used to create a float value.
Example:
f = float(1.1)
Output:
1.1
If we apply this function on an integer value, it will be converted to a float value by adding an extra .0 after the main value
Example:
f1 = float(1)
Output:
1.0
If we want to apply float() function on string value, the string need to be a string of numbers.
Example:
f2 = float('2')
Output:
2.0