Type Casting in Python

Type casting is used to specify the type of a variable. Sometimes you may want to explicitly represent a variable type, here type casting comes in handy. As we know that python is an Object Oriented Programming (OOP) language, it has classes to define the type of the variables. We can use constructor functions for type casting. 

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