Archives November 26, 2022

HOW TO USE TYPECASTING IN PYTHON

Type casting is a method of converting a datatype into a different form to provide meaningful results as per programmer needs.

Basically, python (pvm) either convert the datatypes implicitly or a human should explicitly convert the datatypes

Example: If person X understands english language and X has a computer which understands binary language 0 and 1. In this case, the computer needs to understands as a result of voice recognition of X’s language, then there should be some conversion of letters to binary numbers for the computer to respond. Typecasting also work’s similar to this.

There is an inbuilt function in python called type() which print the datatype of an object.

A real world example will be converting seconds in decimal to integers

time_in_sec = 1.6
print(type(time_in_sec))
print(int(time_in_sec),"second")
O/P:
<class 'float'>
1 second

Any of the datatype can be converted using python functions with the arguments.

There are different ways to convert a datatype to other datatype in python using this feature called typecasting. Using inbuilt functions of python, this can be achieved in a simple way.

To convert string to integer, use ‘int’ function. Here there is a number inside a string which is converted to exact integer by casting.

In this example,

A variable ‘string’ is declared which has been assigned a string ‘1’ object which is automatically recognized by python as string which is called implicit conversion.

In another line, ‘int’ function is added to the variable string which convert the string variable to integer explicitly which is called explicit conversion

#Typecasting of string to integer 

string = '1'

print(type(int(string))) #Explicit conversion
print(type(string)) #implicit conversion
O/P:
1
<class 'int'>
<class 'str'>

Integer can also be converted to string using ‘str’ function. Even though 1 is an integer, which is transformed to string ‘1’

#Typecasting of integer to string

integer = 1

print(str(integer))
print(type(str(integer)))
print(type(integer))
O/P:
1
<class 'str'>
<class 'int'>

Since object with quotes are considered as string, the below string was converted to string again

#Typecasting of integer to string

integer = '1'

print(type(str(integer)))
print(type(integer))
O/P:
<class 'str'>
<class 'str'>

String with letters cannot be converted to integer, which is expected. There should be numbers inside the quotes to be converted.

string = 'string'

print(int(string))

O/P:
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_7236/3795652633.py in <module>
      1 string = 'string'
      2 
----> 3 print(int(string))

ValueError: invalid literal for int() with base 10: 'string'

Similar to integers, decimal’s can also be converted to integer or string

#Typecasting of decimal to string

decimal = 1.0

print(type(str(decimal)))
print(type(decimal))
O/P:
<class 'str'>
<class 'float'>
#Typecasting of decimal to integer 

decimal = '1.0'

print(type(int(decimal)))
print(type(decimal))
O/P:
<class 'int'>
<class 'float'>

#Typecasting of decimal to integer

decimal = 1.0
print(decimal)
print(type(int(decimal)))
print(type(decimal))
O/P:
1.0
<class 'int'>
<class 'float'>
#Typecasting of a boolean value to String or Integer
boolean = True

print(str(boolean))
print(type(boolean))
print(int(boolean))
print(type(boolean))
O/P:
True
<class 'bool'>
1
<class 'bool'>

#Convert string to boolean
str_bool = 'True'
print(str_bool)
print(type(bool(str_bool)))
print(type(str_bool))
O/P:
True
<class 'bool'>
<class 'str'>

Integers can also be converted to binary, octal and hexadecimal values using bin(), oct() and hex() functions

#Convert integer to Binary, Octal and hexadeximal
integer = 1
print(bin(integer))
print(oct(integer))
print(hex(integer))

oct(integer)
O/P:
0o1
0b1
0x1

A typical example which shows that a string and integer cannot be concatenated. This is where typecasting plays a major role.

name = 'kishan'
age = 28
print(name + " you are "+ age + " years old")
O/P:
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_24324/783362701.py in <module>
      1 name = 'kishan'
      2 age = 28
----> 3 print(name + "you are"+ age + "years old")

TypeError: can only concatenate str (not "int") to str

After converting ‘age’ variable to string using str() function, the output is printed without errors

name = 'kishan'
age = 28
print(name + " you are "+ str(age) + " years old")
O/P:
kishan you are 28 years old

A simple function which convert the datatype based on the arguments provided

#Function to convert the datatype of an object in variable
def typecast(var,dt):
#Check the current datatype
    dtype = type(var)
#Convert string to integer
    if dtype == str and dt == 'integer' or dtype == int and dt == 'integer':
        try:
            return int(var)
        except ValueError:
            print("Provide an integer inside quotes")
#Convert integer to string
    elif dtype == int and dt == 'string' or dtype == str and dt == 'string':
            return str(var)

#Convert string to decimal
    elif dtype == str and dt == 'decimal':
        return float(var)
#Convert decimal to integer 
    elif dtype == float and dt == 'integer' or dtype == int and dt == 'decimal':
        return float(var)
    elif var.startswith('0x') or var.startswith('0X'):
        return hex(var)
    elif var.startswith('0b') or var.startswith('0B'):
        return bin(var)
    elif var.startswith('0o') or var.startswith('0O'):
        return oct(var)
    else:
        return "Invalid input"



        
print(typecast('0xA180',None))

Also lists,tuples and sets can also be converted to its counterparts using list(),tuple() and set() functions

l = [1,2,3,4]

print(tuple(l))
print(set(l))

print(type(tuple(l)))
print(type(set(l)))

O/P:
(1, 2, 3, 4)
{1, 2, 3, 4}
<class 'tuple'>
<class 'set'>

t = (1,2,3,4)
print(list(t))
print(set(t))
print(type(list(t)))
print(type(set(t)))

O/P:
[1, 2, 3, 4]
{1, 2, 3, 4}
<class 'list'>
<class 'set'>

s = {1,2,3,4}
print(list(s))
print(tuple(s))
print(type(list(s)))
print(type(tuple(s)))

O/P:
[1, 2, 3, 4]
(1, 2, 3, 4)
<class 'list'>
<class 'tuple'>

Summary:

  • Typecasting will be always useful to convert a datatype to another
  • In a real world scenario, there are lot of conversions which happen from number to text, text to number etc.. which depend on casting of datatypes
  • Typecasting may be useful in string concatenation areas, where a number need to concatenated with a string