Python – Type Casting

Typecasting is a way of converting one data type’s value to another data type’s value. Type conversion is another name for it. Python is an object-oriented programming language that defines data types using classes. As a result, Python – Type Casting may be accomplished by calling the function Object()  method of the data type class in question.

 

  • 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

 

The int() method is used to convert integer literals, float literals, and string literals into integer data types in the example below.

 

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 following example shows how to convert integer, float, and string literals to float data types using the float() method.

 

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

The str() method is used to transform several data types into string data types in the example below using Python – Type Casting.

 

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

Leave a Reply

Your email address will not be published.