Python Type Casting

In Python, Type Casting is a process in which we convert a literal of one type to another.

Inbuilt functions int(), float() and str() shall be used for typecasting.

  • int() can take a float or string literal as argument and returns a value of class 'int' type.
  • float() can take an int or string literal as argument and returns a value of class 'float' type.
  • str() can take a float or int literal as argument and returns a value of class 'str' type.

In this tutorial, we shall learn how to type cast a literal between integer, float, and string.

Type Cast int to float and string

In this example, we shall take an integer literal assigned to a variable. Then we shall typecast this integer to float using float() function. Next, we shall typecast the integer to string using str().

We shall print both the value and type of the float and string variables.

Python Program

# Integer
n = 100

# Float
f = float(n)
print(f)
print(type(f))

# String
s = str(n)
print(s)
print(type(s))
Run Code Copy

Output

Run the above Python program, and you shall see the following output printed to the console output.

100.0
<class 'float'>
100
<class 'str'>

Type Cast float to int and string

In the following program, we shall initialize a variable with float value. In the next statement, we typecast this float to integer using int(). Later we typecast the float to string.

Python Program

# Float
f = 100.05

# Integer
n = int(f)
print(n)
print(type(n))

# String
s = str(f)
print(s)
print(type(s))
Run Code Copy

Output

100
<class 'int'>
100.05
<class 'str'>

The decimal value is gone when you typecast float to int.

Type Cast string to int and float

In this example, we shall use int() and float() to typecast a string literal to integer and float.

Python Program

# String
s = '132.65'

# Typecast to integer
n = int(s)
print(n)
print(type(n))

# Typecast to float
f = float(s)
print(f)
print(type(f))
Run Code Copy

Output

Run the above Python program and you shall see that the string is typecasted to integer and float.

132
<class 'int'>
132.0
<class 'float'>

Note: Please note that, if you have decimal point in the string, you cannot typecast that directly to an integer. You should first typecast string to float and then that to integer. Following is a quick code snippet for the same.

# String
s = '132.564'

# Typecast to integer
n = int(float(s))
Run Code Copy

Summary

In this tutorial of Python Examples, we learned how to typecast one datatype to another in between integer, float and string. Also, well detailed examples are provided to demonstrate the typecasting.

Code copied to clipboard successfully 👍