1.

Python Type Casting

Answer»

Type casting is basically a conversion of variables of a particular datatype into some other datatype, such that the conversion is valid.

Type casting can be of two types:


  • Implicit Type Casting: In implicit type casting, the python compiler internally typecasts one variable into another type without the external action of the user.
    Example:
int_num = 100
float_num = 1.01
ans = int_num + float_num
print(type(int_num))
print(type(float_num))
# ans is implicitly typecasted to float type for greater precision
print(type(ans))

  • Explicit Type Casting: In explicit type casting, the user explicitly forces the compiler to convert a variable from one type to another. The different ways of explicit typecasting are given below:

1. Integer to String or Float:

To typecast an integer into a string type, we use the str() method. Similarly, to typecast it into a float type, we use the float() method.

For example:

>>> var = 123
>>> str(var)
'123'
>>> var = 123
>>> float(var)
123.0

2. Float to Integer:

To typecast a float datatype into an integer datatype, we use the int() method.

For example:

>>> var = 7.8
>>> print(int(var))
7


Discussion

No Comment Found