Type Casting in Python

 Type Casting in Python 

Type Casting in Python

A method to convert the variable data type into a certain or required data type.

In python, it is using constructor functions like int(), string(), float(), etc. 

two types of Type Casting in Python –

·         Implicit Type Casting

·         Explicit Type Casting

 

Implicit Type Conversion

Implicit type conversion is performed automatically by the interpreter, without user intervention.

Python automatically converts one data type to another data type.

In this process, no need for any user involvement.

Python promotes the conversion from lower data type to higher.

This type of conversion or type casting is also called Up-Casting.

Example:-

# implicit type Casting

# Python automatically converts

# a to int

a = 7

print(type(a))

 

# Python automatically converts

# b to float

b = 3.0

print(type(b))

 

# Python automatically converts

# c to float as it is a float addition

c = a + b

print(c)

print(type(c))

 

# Python automatically converts

# d to float as it is a float multiplication

d = a * b

print(d)

print(type(d))

Output:

<class 'int'>
<class 'float'>
10.0
<class 'float'>
21.0
<class 'float'>
 

-----------------------------------------------------------------------------------------------------

Explicit Type Casting

In this method, Python needs user involvement to convert the variable data type into a certain data type in order to the operation required.

the user or programmer converts the data type of an object to the required data type.

Python use predefined functions like int(), float(), str(), bool() etc to perform explicit type conversion.

 

Syntax:

(Required datatype) (Expression)
           ↓
(Desired type)

type casting can be done by following data type functions:

·         Int(): take float or string as an argument and return int type object.

·         float(): take int or string as an argument and return float type object.

·         str(): take float or int as an argument and return string type object.

 

examples of type casting:

Type Casting int to float:

# int variable

a = 5

# typecast to float

n = float(a)

 print(n)

print(type(n))

Output:

5.0

<class 'float'>

 

Type Casting float to int:

float data type into integer data type with int() function.

# int variable

a = 5.9

 # typecast to int

n = int(a)

 print(n)

print(type(n))

Output:

5

<class 'int'>

 

Type casting int to string:

casting int data type into string data type with str() function.

# int variable

a = 5

 # typecast to str

n = str(a)

 print(n)

print(type(n))

Output:

5

<class 'str'>

 

Type Casting string to int:

casting string data type into integer data type with int() function.

# string variable

a = "5"

 # typecast to int

n = int(a)

 print(n)

print(type(n))

Output:

5

<class 'int'>

 

Type Casting String to float:

casting string data type into float data type with float() function.

# string variable

a = "5.9"

 # typecast to float

n = float(a)

 print(n)

print(type(n))

Output:

5.9

<class 'float'>

 

Casting float value to an integer

Example:-  

pi = 3.14 

# float number

print(type(pi))

# Output

class 'float'

 

Casting Boolean value to an integer

num1 = int(flag_true)

num2 = int(flag_false)

 print("Integer number 1:", num1) 

# Output

 1

print(type(num1)) 

 # Output

 class 'int'

 

print("Integer number 2:", num2)

# 0

print(type(num2))

# class 'int'

 

Casting a string to an integer

string_num = "225"

print(type(string_num))

# Output class 'str'

  

Float type conversion

In float type conversion use a built-in function  float() .

This function converts variables of other types to float types.

Casting integer to float

num = 725

print(type(num))

# Output class 'int'

 

# converting float to integer

num1 = float(num)

 print("Float number:", num1)

# Output 725.0

 

Casting Boolean to float

flag_true = True

flag_false = False

print(type(flag_true))

# Output class 'bool'

 

Casting string to float

string_num = "725.535"

print(type(string_num))

# Output class 'str'

 

convert any type to float type, but we cannot cast complex to float type.

While converting string type to float type, a string must contain an integer/decimal value of base-10.

 

Complex type conversion

In complex type conversion, use the built-in function complex() to convert values from other types to the complex type.

Value can be any type including int, float, bool, str.

The complex function has the following two forms for conversion.

complex(x):

To convert a value x into a complex type. In this form, the real value is x, and the imaginary value is 0.

complex(x, y):

To convert the value x and y into a complex type. In this form, the real value is x, and the imaginary is y.

 

Casting integer type to complex type

r_num = 135

print(type(r_num)) # class 'int'

 # converting int to complex(x)

c_num = complex(r_num)

 print("Complex number:", c_num)

# Output (135+0j)

print(type(c_num))

# class 'complex'

 # converting int to complex(x, y)

r_num, i_num2 = 135, 235

c_num = complex(r_num, i_num2)

 print("Complex number:", c_num)

# Output (135+235j)

print(type(c_num))  # class 'complex'

 

Casting float type to complex type

r_num = 53.250

print(type(r_num))  # class 'float'

 # converting float to complex(x)

c_num = complex(r_num)

 print("Complex number:", c_num)

# Output (53.25+0j)

print(type(c_num)) 

# class 'complex'

 

Casting Boolean type to complex type

boolean_true = True

print(type(boolean_true))  # class 'bool'

 

Bool type conversion

uses the built-in function bool() to convert values of other types to bool types.

This function returns two values, either True or False.

convert any type of value to bool type, and the output for all values will be True, Except 0, which is False.

If convert an empty string to a Boolean it will be converted to Boolean False.

The bool True is 1 and False is 0.

Every non-zero value is treated as True.

 

Casting integer to Boolean type

num1 = 10

num2 = 0

print(type(num1))  # class 'int'

 # Convert into to bool

b1 = bool(num1)

b2 = bool(num2)

 print(b1)

# Output True

print(b2)

# Output False

 print(type(b1))

# class 'bool'

 

Casting float to Boolean type

f_num1 = 25.35

f_num2 = 0.0

print(type(f_num1))  # class 'float'

 # Convert float into to bool

b1 = bool(f_num1)

b2 = bool(f_num2)

 print(b1)

# Output True

 print(b2)

# Output False

 print(type(b1))

# Output class 'bool'

 

Casting string to Boolean type

s1 = "False"

s2 = "True"

s3 = "812"

s4 = ""

print(type(s1))  # class 'str'

 # Convert string into to bool

b1 = bool(s1)

b2 = bool(s2)

b3 = bool(s3)

b4 = bool(s4)

 print(b1)  # True

print(b2)  # True

print(b3)  # True

print(b4)  # False

print(type(b1))  # class 'bool'

 

Casting complex type to Boolean type

c1 = 33 + 9j

c2 = 0 + 0j

print(type(c1))  # class 'complex'

 # Convert complex value into to bool

b1 = bool(c1)

b2 = bool(c2)

 print(b1)  # True

print(b2)  # False

print(type(b1))  # class 'bool'

 

String type conversion

In str type conversion, use the built-in function str() to convert converts variables of other types to a string type.

This function returns the string type of object (value).

Casting int to str type

num = 15

print(type(num))  # class 'int'

 # converting int to str type

s1 = str(num)

print(s1)

# Output '15'

print(type(s1))

# Output class 'str'

 

Casting float type to str type

num = 75.35

print(type(num))  # class 'float'

 # converting float to str type

s1 = str(num)

print(s1)

# Output '75.35'

print(type(s1))

# Output class 'str'

 

Casting complex type to str  type

complex_num = 15 + 5j

print(type(complex_num))  # class 'complex'

 # converting complex to str type

s1 = str(complex_num)

print(s1)

# Output '(15+5j)'

 print(type(s1))

# class 'str'

# converting bool to str type

s1 = str(b1)

s2 = str(b2)

print(s1)

# Output 'True'

print(s2)

# Output 'False'

print(type(s1))  # class 'str'

 

the most commonly used built-in functions to perform conversion from one data type to another.

Sr.No.

Functions & Description

1.

int(x [,base])
Converts x to an integer. Base specifies the base of x if x is a string.
By default, the base is 10, if it is not specified, which is decimal value.

2.

float(x)
Converts x to a floating-point number.

3.

complex(real [,imag])
Creates a complex number.

4.

bin(x)
Converts an integer to a binary value.

5.

bool(x)
Converts object x to a boolean value, either True or False.

6.

str(x)
Converts object x to a string representation.

7.

repr(x)
Converts object x to an expression string (i.e., a printable representation of the given x).

8.

eval(str)
Evaluates a string and return an object (often the object would be an integer).

9.

tuple(s)
Converts s to a tuple.

10.

list(s)
Converts s to a list.

11.

set(s)
Converts s to a set.

12.

dict(d)
Creates a dictionary. d must be a sequence of (key,value) tuples.

13.

frozenset(s)
Converts s to a frozen set.

14.

chr(x)
Converts an integer to its corresponding ASCII character.

15.

ord(x)
Converts a single character to its corresponding ASCII code, which is integer value.

16.

hex(x)
Converts an integer to its corresponding hexadecimal string.

17.

oct(x)
Converts an integer to its corresponding octal string.

 

Details:-

1.   int(x [,base]):

Take a float, bool, or string literal as an argument and returns a value of class 'int' type.

Can’t convert a complex number into an int type.

When converting a string type to an int type, a string must contain an integral (numerical) value only and may have a varied base.

Every numerical value has a base, for example:

The decimal value uses the digits 0 to 9 and has a base of 10

The binary value uses the digits 0 or 1 and has a base of 2

The octal value uses the digits from 0 to 7 and has a base of 8

Hexadecimal uses the digit from 0 to 9 plus the letters A through F, and has a base of 16

Example:

# float to int conversion

 length = 5.1926    # floating point number

type(length)        # type() function is used to get the type of a value or a variable

 new_length = int(length)   #converting float to int type using int() function

print(new_length)

type(new_length)

  # string to int conversion

 num_str = "1234"

type(num_str)

 num_int = int(num_str)   #converting string to int type using int() function

print(num_int)

type(num_int)

Output:

 

 

# float to int conversion

 <class 'float'>

 5

<class 'int'>

 # string to int conversion

 <class 'str'>

 1234

<class 'int'>

 

2. float(x):

The float() function is used to convert a given data type to floating-point numbers.

float(x) function can take an int, bool or string literal as argument and returns a value of class 'float' type.

Example:

# int to float conversion

 num_int = 1024   # An integer value

type(num_int)

 new_num = float(num_int)   #converting an integer to a floating-point number using float() function

print(new_num)

type(new_num)

Output:

<class 'int'>

 1024.0

<class 'float'>

 

3. complex(real [,imag]):

complex() function is used to convert an int, float, bool or a string literal to 'complex' type.

The complex function has the following two forms for conversion:

complex(x): To convert a value x into a complex type. In this form, the real part is  x, and the imaginary part is 0.

complex(x, y): To convert the value x and y into a complex type. In this form, the real part is x, and the imaginary part is y.

Example:

# int to complex conversion

 num_int = 7

 num_c = complex(num_int)   #converting an integer to a complex number using complex() function

print(num_c)

type(num_c)

Output:

(7+0j)

<class 'complex'>

 

4. bin(x):

The bin(x) function takes an integer x as an argument and returns the binary representation of x in a string format.

Example:

# int to binary conversion

 a = 1

type(a)

 b = bin(a)    #converting an integer to a binary value using bin() function

print(b)

type(b)

 #or

bin(a)

Output:

<class 'int'>

 0b1

<class 'str'>

 '0b1'

 

5. bool(x):

The bool(x) Converts object x to a boolean value, either True or False.

The object x can an integer, float, complex number, or any expression.

An integer, float, or complex number set to zero returns False.

And, An integer, float, or complex number set to any other numbers, positive or negative returns True.

Example:

# int to bool conversion

 x = 1

  y = bool(x)    #converting an integer to a boolean value using bool() function

print(y)

type(y)

 a= 0

 b = bool(a)

print(b)

type(b)

Output:

True

<class 'bool'>

 False

<class 'bool'>

 

6. str(x):

The str(x) function takes an object x as an argument and returns the string format of the given object x.

Objects can be any object. But generally, int, float, complex, or boolean is used.

If don’t provide any object as an argument inside the str() function, it returns an empty string.

Example:

# int to string conversion

 n_int = 999

type(n_int)

 n_str = str(n_int)    #converting an integer to a string using str() function

print(n_str)

type(n_str)

 # or

str(999)

 str()    # not providing any argument inside the parentheses of str() function.

Output:

<class 'int'>

 999

<class 'str'>

 '999'

 ' '    # An empty sting is printed

 

7. repr(x):

The repr(x) converts object x to an expression string (i.e., a printable representation of the given x).

Object x can be of any data type or you can say object x can be any object.

repr() takes only one argument at a time.

Example:

# complex to expression string conversion

 x = 3 + 5j     # declaring a complex number x

type(c)

 new_obj = repr(x)    #converting a complex number to a expression string using repr() function

print(new_obj)

type(new_obj)

 #or

 repr(x)

type(repr(x))

Output:

<class 'complex'>

 (3+5j)

<class 'str'>

 '(3+5j)'

<class 'str'>

 

8. eval(str):

The eval(str) function takes an expression in the form of a string as an argument and converts it to the result of the evaluated expression (most often the return type would be a number).

Also, optionally global and locals can be used as an argument inside the eval function, but the globals must be represented as a dictionary and the locals as a mapped object.

The syntax of the eval function is as shown below:

eval(expression, [globals[, locals]])

Example:

# passing an expression inside the parentheses of eval() function.

 a = eval('3*2+1-3')    # passing an expression in the form of a string inside the parentheses of eval() function

print(a)

type(a)

Output:

4

 <class 'int'>

 

9. tuple(s):

The tuple(s) function takes an object s as an argument and converts s to a tuple.

Example:

# string to tuple conversion

 s = "python"

type(s)

 t = tuple(s)   #converting a string to tuple using tuple() function

print(t)

type(t)

Output:

<class 'str'>

 ('p', 'y', 't', 'h', 'o', 'n')

<class 'tuple'>

 

10. list(s):

The list(s) function takes an object s as an argument and converts s to a list.

Objects can be a sequence (string, tuples) or collection (set, dictionary), or any iterable object.

If no parameters are passed inside the parentheses of the list() function, it returns an empty list.

Example:

# tuple to list conversion

 tup = (2, 4, 6, 8)

type(tup)

 lst = list(tup)   #converting a tuple to a list using list() function

print(lst)

type(lst)

 list()    # not providing any argument inside the parentheses of list() function.

Output:

<class 'tuple'>

 [2, 4, 6, 8]

<class 'list'>

 [ ]    # An empty list is created

 

11. set(s):

The set(s) function takes an object s as an argument and converts s to a set.

Objects can be any iterable sequence like a list, tuple, or dictionary.

Example:

# list to set conversion

 lst = [1, 2, 3, 4, 5]

type(lst)

 s = set(lst)   #converting a list to a set using set() function

print(s)

type(s)

Output:

<class 'list'>

 {1, 2, 3, 4, 5}

<class 'set'>

 

12. dict(d):

The dict(d) function takes an object d as an argument and creates a dictionary. d must be a sequence of (key, value) tuples.

Example:

# tuple to dictionary conversion

 # initializing (key, value) tuple

tup = ((1, 'one') ,(2, 'two'), (3, 'three'))

type(tup)

 d = dict(tup)   #converting a tuple to a dictionary using dict() function

print(d)

type(d)

Output:

<class 'tuple'>

 {1: 'one', 2: 'two', 3: 'three'}

<class 'dict'>

 

13. frozenset(s):

The frozenset(s) function takes an iterable object s as an argument and converts s to a frozen set.

The iterable object can be a list, tuple, set, or any other iterable.

Example:

 

# set to frozenset conversion

 s = {'a', 'e', 'i', 'o', 'u'}    # set of all the vowels in english alphabets

type(s)

 fset = frozenset(s)    # converting a set to frozenset using frozenset() function

print("frozenset is : ", fset)

type(fset)

Output:

<class 'set'>

 frozenset is :  frozenset({'i', 'a', 'o', 'e', 'u'})

<class 'frozenset'>

 

14. chr(x):

The chr(x) function takes only one integer as an argument and converts that integer x to its corresponding ASCII character.

Example:

# integer to its corresponding ASCII character conversion

 num_int = 65

type(num_int)

 c = chr(num_int)    # converting an integer to ASCII character using chr() function

print(c)

type(c)

Output:

<class 'int'>

 A     # ASCII character of 65 is 'A'

<class 'str'>

 

15. ord(x):

This is just the inverse of chr() function.

The ord(x) function takes only one character as an argument and converts that character x to its corresponding ASCII code, which is integer value.

Example:

# a single character to its corresponding ASCII code conversion

 ch = 'z'     # declaration of a single character 'z' (lowercase z)

type(ch)

 code = ord(ch)    # converting a character to its corresponding ASCII code using ord() function

print(code)

>>> type(code)

Output:

<class 'str'>

 122

<class 'int'>

 

16. hex(x):

The hex(x) function takes an integer x as an argument and converts it to its corresponding hexadecimal string.

Example:

# integer to its corresponding hexadecimal string conversion

 num_int = 10

type(num_int)

 H = hex(num_int)    # converting an integer to hexadecimal string using hex() function

print(H)

type(H)

 #or

hex(10)

type(hex(10))

Output:

<class 'int'>

 0xa

<class 'str'>

 '0xa'

<class 'str'>

 

17. oct(x):

The oct(x) function takes an integer x as an argument and converts it to its corresponding octal string.

Example:

num_int = 25

type(num_int)

 new_str = oct(num_int)    # converting an integer to octal string using oct() function

print(new_str)

type(new_str)

 #or

oct(25)

type(oct(25))

Output:

<class 'int'>

 0o31

<class 'str'>

 '0o31'

<class 'str'>

 ================================================================

Post a Comment

0 Comments