Python Tutorial Python Advanced Python References Python Libraries

Python - Type Casting



The type casting is a method of converting the value of one data type to another data type. It is also known as type conversion. Python is an object-orientated language, and it uses classes to define data types. Hence, the type casting can be achieved by using constructor function of given data type class.

  • int()- It converts different data types into an integer. Datatypes that can be used with this function are an integer literal, a float literal and a string literal (provided the string represents a whole number).
  • float()- It converts different data types into a float number. Datatypes that can be used with this function are an integer literal, a float literal and a string literal (provided the string represents an integer or a float number).
  • str()- It converts all data types into a string.

Type Casting to integer data type

In the example below, int() function is used to convert integer literal, float literal and string literal into an integer data type.

x = int(1)
print(x)

y = int(10.55)
print(y)

z = int('100')
print(z)

The output of the above code will be:

1
10
100

Type Casting to float data type

The example below describes how to use float() function to convert integer literal, float literal and string literal into a float data type.

p = float(1)
print(p)

q = float(10.55)
print(q)

r = float('100')
print(r)

s = float('1000.55')
print(s)

The output of the above code will be:

1.0
10.55
100.0
1000.55

Type Casting to string data type

In the example below, str() function is used to convert different data types into string data type.

x = str(10)
print(x)

y = str(100.55)
print(y)

z = str('1000')
print(z)

The output of the above code will be:

10
100.55
1000