# What Is Type Conversion in Python

7K

A Python data type conversion method is called a conversion of type. We can convert objects of string type to a numeric value, convert them to various container types, etc. Python primarily provides two types of conversion methods: implicit conversion type and explicit conversion type.

## Implicit Type Conversion in Python:

In Python, the conversion of data type is called an implicit conversion of data type when it takes place duringcompilation, or duringrun time. Python manages the conversion of the implicit data type, so we do not directly convert the data type to another data type.

Implicit type casting means conversion without losing the original significance of data forms. This form of typecasting is important if you want to adjust the data without changing the importance of the values stored in the variable.

Conversion of the implicit type occurs automatically if a value is copied to its compatible type. Strict guidelines for conversion of forms shall be enforced during conversion. If the operands are of two different data types, then the operand with a lower data type will be automatically converted to a higher data type.

Let us add two Python variables of two types of data, and store the result in a variable, and see if the Python compiler converts the resultant variable data type.

value1 = 10
value2 = 10.5
sum = value1 + value2
print (sum)
print (type (sum)) #type() is used to display the datatype of a variable 

Output:

20.5
<class ‘float’> 

In the example above, we have taken and added two variables of integer and float data. In addition, we have declared and stored the result of the added variable called ‘sum’. By checking the sum variable data type, the Python compiler transforms the sum variable data type automatically into the float data type. This is referred to as conversion of implicit type.

The explanation for converting the sum variable into the floating data type is that if the compiler had converted it into the integer data type, the fractional part had to be omitted and data loss would have occurred. Python thus turns smaller data types into larger data types to avoid data loss.

In certain instances, Python cannot use implicit conversion and explicit conversion of the form enters into play.

## Explicit Type Conversion in Python:

Users convert the data type of an object to the data type required by Explicit Type Conversion. To perform explicit type conversion, we use predefined functions such as int(), float(), str().

This conversion form is also called typecasting as the user casts (changes) the object data type.

The conversion of the explicit type happens when the programmer specifies the program clearly and explicitly. There are several built-in Python functions for explicit form conversion.

Syntax:

(required_data type)(expression)
Example:
value1 = 100
value2 = “300”
result1 = value1 + value2
value2 = int(value2)
result2 = value1 + value2
print(result2) 

Output:

Traceback (most recent call last):
File “”, line 1, in
TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’
400 

Variable value1 is the data type number and variable value2 is the data type string. If these two entries are inserted and the value is stored in the variable called result1, a TypeError happens as seen in the output. So, we must use explicit casting to perform this operation.

We’ve turned the variable value2 to int and then inserted variable value1 and value2. The amount is stored in the result2 variable and 400 is shown in the output.

### int(a, base):

This function int (a, base) convertsany data type into an integer. It is a method to convert number stringain the givenbasevalue to decimal value. Base defines the base in which a string is transformedif the data type is a string. Base is set to 10 by default.

Example:

try:
a = “10010”
# string converting to int base 2
c = int(a,2)
print(‘string converted to int base 2 : ‘, c)
# string converting to int base 10
c = int(a)
print(‘string converted to int base 10: ‘, c)
except TypeError as typeError:
print(typeError) 

Output:

string converted to int base 2 : 18
string converted to int base 10: 10010 

### float():

A floating point number from a number or string is returned by float() method.

• Syntax:
• float(a)
• Types of argument, the method accepts:
• A number:May be either an integer or a number of a floating-point.
• A string:

Must have some type of number.

• The method ignores any left or right spaces and new lines.
• It is possible to use mathematical operators.
• Can include NaN, Infinity or Inf (any cases)

Values that can be returned by float() according to the passed statement:

• The equivalent floating point number is then returned if an argument is passed.
• The method returns 0.0 when no argument is passed.
• If a string is passed which does not match a number of decimal points, then an error is raised.
• If a number exceeds the Python float range, OverflowError is generated.

Example:

try:
a = “10010”
# string converting to float
c = float(a)
print(‘string converted to float: ‘, c)
except TypeError as typeError:
print(typeError)  

Output:

string converted to float: 10010.0

### ord():

The ord() function in Python accepts an argument for a string in unit length and returns the Unicode equivalence of the passed argument. In other words, the ord() function returns the integer of the Unicode point of the character in the Unicode case or the byte value in the case of an 8-bit argument.

Syntax:
ord("string") 

Example 1:

We find the Unicode code point values of an integer, a character, and a special character. The first 128 Unicode points are similar to those of ASCII, which means that the Unicode points are the same as the ASCII values of the passed strings of length 1.

# unicode code point of integer
print("The ASCII value of 9 is",ord('9'))
# unicode code point of alphabet
print("The ASCII value of B is",ord('B'))
# unicode code point of special character
print("The ASCII value of ! is",ord('!')) 

Output:

The ASCII value of 9 is 57
The ASCII value of B is 66
The ASCII value of ! is 33 

Example 2:

AnErroris raised when the length of the string is not equal to 1

value1 =ord('AB')
valueprint(value1)
Runtime Error:
Traceback (most recent call last):
File “/home/f988dfe667cdc9a8e5658464c87ccd18.py”, line 6, in
value1 = ord(‘AB’)
TypeError: ord() expected a character, but string of length 2 found 

### hex():

The hex() function is one of Python3’s built-in functions used to convert the integer into a suitable hexadecimal form for the number of the integer.

Synta:

hex(x)

The hex() function converts and returns the integer in a string form to the corresponding hexadecimal number.

The hexadecimal string returned begins with the prefix 0x which means it is hexadecimal.

Example 2:

try:
a = 5
c = hex(a) #converts 5 into hexadecimal value
print(“hexadecimal value of 5 : “, c)
except TypeError as typeError:
print(typeError)   

Output:

hexadecimal value of 5 : 0x5

Example 2:Passing the types other than the integer to the hex() method causes an error.

try:
a = ‘4’
c = hex(a) #converts 4 into hexadecimal value
print(“hexadecimal value of 4 : “, c)
except TypeError as typeError:
print(typeError)   

Output:

‘str’ object cannot be interpreted as an integer

### oct():

oct() is one of Python3’s built-in methods. The oct() method is an integer and returns its octal representation in a string format.

Syntax :

oct(x)

Example:

print("The octal representation of 23 is "+oct(23))
print("The octal representation of the"" ascii value of 'z' is "+oct(ord('z')))
# Binary representation of a number # can be passed as a parameter
# For 23, Binary is 0b10111
print("The octal representation of the binary"" of 23 is "+oct(0b10111))
# For 23, Hexadecimal is 0x17
print("The octal representation of the binary"" of 23 is "+oct(0x17)) 

Output:

The octal representation of 23 is 0o27
The octal representation of the ascii value of 'z' is 0o172
The octal representation of the binary of 23 is 0o27
The octal representation of the binary of 23 is 0o27

### tuple():

This function is used toconvert a data type into a tuple.

A tuple is generated by placing all items (elements), separated by commas, inside the parentheses (). The parentheses are optional, but use of them is a great practice.

This function takes a single iterable parameter (optional). It's an iterable object (list, range, etc.). The corresponding tuple is generated, if an iterable is transferred. If you don't move the iterable, empty tuples are made.

Syntax:

tuple(iterable)

This feature accepts a single iterable parameter (optional). It is an iterable object(list, range etc.). The corresponding tuple is formed when an iterable is moved. If you don’t move the iterable, you build empty tuple.

# when parameter is not passed
tuple1 =tuple()
print(tuple1)
# when an iterable(e.g., list) is passed
list1=[ 1, 2, 3, 4]
tuple2 =tuple(list1)
print(tuple2)
# when an iterable(e.g., dictionary) is passed
dict={ 1: 'one', 2: 'two'}
tuple3 =tuple(dict)
print(tuple3)
# when an iterable(e.g., string) is passed
string ="india"
tuple4 =tuple(string)
print(tuple4) 

Output:

()
(1, 2, 3, 4)
(1, 2)
('i', 'n', 'd', 'i', 'a') 

set():
set() method is used to convert all of the iterable elements to the iterable sequence, commonly referred to as Set. 

syntax:

set(iterable)

Example:

# initializing list
lis1 =[ 3, 4, 1, 4, 5]
# initializing tuple
tup1 =(3, 4, 1, 4, 5)
# Printing iterables before conversion
print("The list before conversion is : "+str(lis1))
print("The tuple before conversion is : "+str(tup1))
# Iterables after conversion are notice distinct and elements
print("The list after conversion is : "+str(set(lis1)))
print("The tuple after conversion is : "+str(set(tup1))) 

Output:

The list before conversion is : [3, 4, 1, 4, 5]
The tuple before conversion is : (3, 4, 1, 4, 5)
The list after conversion is : {1, 3, 4, 5}
The tuple after conversion is : {1, 3, 4, 5}

### list():

This function converts every type of data into a list type.

The list() constructor returns the list.

• If no parameters are passed, an empty list will be returned.
• When iterable is passed as a parameter, a list of iterable elements is generated.
# empty list
print(list())
# vowel string
vowel_string = 'aeiou'
print(list(vowel_string))
# vowel tuple
vowel_tuple = ('a', 'e', 'i', 'o', 'u')
print(list(vowel_tuple))
# vowel list
vowel_list = ['a', 'e', 'i', 'o', 'u']
print(list(vowel_list)) 

Output:

[]
['a', 'e', 'i', 'o', 'u']
['a', 'e', 'i', 'o', 'u']
['a', 'e', 'i', 'o', 'u'] 

### dict():

This function is used to convert a tuple of order (key, value) into a dictionary.

Example:

# keyword argument is not passed
numbers1 = dict([('x', 5), ('y', -5)])
print('numbers1 =',numbers1)
# keyword argument is also passed
numbers2 = dict([('x', 5), ('y', -5)], z=8)
print('numbers2 =',numbers2)
# zip() creates an iterable in Python 3
numbers3 = dict(dict(zip(['x', 'y', 'z'], [1, 2, 3])))
print('numbers3 =',numbers3) 

Output:

numbers1 = {'y': -5, 'x': 5}
numbers2 = {'z': 8, 'y': -5, 'x': 5}
numbers3 = {'z': 3, 'y': 2, 'x': 1}

### str():

This function is used toconvert a value (integer or float) into a string.

Example:

num =100
s =str(num)
print(s, type(s))
num =100.1
s =str(num)
print(s, type(s)) 

Output:

100 <class 'str'>
100.1 <class 'str'> 

### complex(real,imag)

When real and imaginary parts are given, the complex() method returns a complex number, or converts a string to a complex number.

Complex() normally takestwo parameters:

• real – real part. If the real is omitted, the default is 0.
• imag-an imaginary part of it. It's 0 by default if imag is omitted.

If this form is the first parameter to be passed on, it will be construed as a complex number. In that case, you do not pass the second parameter.

Example:

z = complex(2, -3)
print(z)
z = complex(1)
print(z)
z = complex()
print(z)
z = complex('5-9j')
print(z) 

Output:

(2-3j)
(1+0j)
0j
(5-9j)

### chr(number)

The chr() method returns the character (string) from the integer (represents unicode code point of the character).

Only one integer is used as an argument in the chr() method. The range will vary between 0 and 1,1141,111 (0x10FFFF in base 16). The chr() method returns an integer character with a number unicode. The method returns a value error if an integer is passed beyond the range.

Example:

print(chr(97))
print(chr(65))
print(chr(1200)) 

Output:

a
A
Ұ 

Conclusion:

Typecasting is also referred to as type conversion. It implies that one data form is transformed into another. It is often called type promotion as the smaller data type is converted into a bigger one.

When the compatible data type is found, implicit type conversion operates automatically.

### Abhresh Sugandhi

Author

Abhresh is specialized as a corporate trainer, He has a decade of experience in technical training blended with virtual webinars and instructor-led session created courses, tutorials, and articles for organizations. He is also the founder of Nikasio.com, which offers multiple services in technical training, project consulting, content development, etc.