Typecasting in Python. Topic 7

Typecasting in Python

The conversion of one data type into another data type is known as type casting in Python or type conversion in Python.

If you don’t know about different data types read this post first :

Python supports a wide variety of functions or methods like: int(), float(), str(), ord(), hex(), oct(), tuple(), set(), list(), dict(), etc. for the type casting in python.

Definition: The meaning of typecasting is to convert one data type into another data type. In Python programming, we can do it very easily with a built-in function. With the help of these built-in functions, we can convert the value of one type into another type. So let’s understand this through some examples.

i) float to int:

float_number = 3.14
int_number = int(float_number)
print(int_number)
print(type(int_number))  #type function check the datatype

The Output Of This Code Will Be:

Output
3
<class 'int'>

ii) int to float:

int_number = 42
float_number = float(int_number)
print(float_number)  
print(type(float_number))  #type function check the datatype

The Output Of This Code Will Be:

Output
42.0
<class 'float'>

iii) int to str:

number = 123
str_number = str(number)
print(str_number) 
print(type(str_number))   #type function check the datatype

The Output Of This Code Will Be:

Output
123
<class 'str'>

iv) tuple to list:

tuple_values = (1, 2, 3)
list_values = list(tuple_values)
print(list_values)  
print(type(list_values))  #type function check the datatype

The Output Of This Code Will Be:

Output
[1, 2, 3]
<class 'list'>

I hope you understand Typecasting in Python. If you do not understand this topic just comment below with your email ID, and I will mail back to you.

Finite number of  lines code and infinite possibilities

Programmer, Arpan Bera

Leave a Reply

Your email address will not be published. Required fields are marked *

ABOUT ME
Arpan Bera

Coding is like Love – everyone can start, but only a few finish without errors

Keep Updated to our News and Blog