Introduction to Type Casting in Python

Posted by PythonStacks on October 23, 2020

Introduction

This quick tutorial will guide on how to change an object from one type to another in python.

Variables in python have data types just as many other languages. There may be times when you will want to specify or change the data type of a particular variable.

This process of changing a variable's type to another is known as casting or type-casting.

Casting in python is done mainly through these pre-defined inbuilt functions:

  • int()   -  This function is used to convert data into an integer type.
  • float() -    Converts the given arguments into a float.
  • str()   -    Converts the given arguments to a string.

 

Converting Strings to Integers


# Converting to integer
num = int("345")    # num will be 345

# to verify its type
print(type(num))

Here, a string, "345" is passed into the int() function to be converted to an integer before it's stored in the num variable.   

You can verify the type by using the type() function. When you run the code above, it gives :

<class 'int'>    # output

 

Converting Floats to Integers


# Converting a float to an integer
age = int(32.4)

# to verify its type
print(age)
print(type(age))

Here, a string, "345" is passed into the int() function to be converted to an integer before it's stored in the num variable.   

You can verify the type by using the type() function. Running the code :
 

# output

32
<class 'int'>

 

Converting Integers to Floats


# Converting a integer to float
number = float(504)

# to verify its type
print(number)
print(type(number)


Converting  to Strings


string_num = str(34)  # string_num will be 's4'
x = str(45.56)        # x will be '45.56'
name = str("john")       # name will be "john"

a = str(True)         # a becomes 'True'

 

Case Study

If you want to concatenate an integer such as 12 with a string, you’ll need to get the value '12', which is the string form of 12. The str() function can be passed an integer value and will evaluate to a string version of it:

>>> print("I am " + str(12) + " years old")
I am 12 years old 

 

If you want to convert input received from a user to integer:

age = int(input("Please enter your age: "))

This program converts whatever the user inputs to an integer. If the input received from the user in an invalid integer literal (String or Boolean), an error will be raised since it cannot convert to integer.


Share This Post

Tweet Share Share Share

Subscribe to receive updates!

0 Comments

Leave a comment

* Email would not published