What are different data conversion methods in Python?



Type conversion is the transformation of a Python data type into another data type. Implicit type conversion and explicit type conversion are the two basic categories of type conversion procedures in Python.

We will cover the following topics in this article −

  • Implicit Type Conversion in Python is carried out by the Python interpreter automatically.

  • In Python, explicit type conversion must be performed directly by the programmer.

Let's study more about these two approaches in depth and with some illustrations.

Implicit Type conversions

Implicit type conversion occurs when the Python interpreter automatically changes an object's data type without the programmer's intervention.To avoid any data loss during the runtime, the smaller data type is converted into a higher data type.

We don't need to explicitly use any function in the code because the conversion happens automatically.

Note − A high-level language is translated into a computer-understandable language by an interpreter. Each line of code is read individually by the interpreter before being executed directly.

Example

Following is an example of implicit type conversions

a = 13 print("The Data Type of Variable a is:",type(a)) b = 6.9 print("The Data Type of Variable b is:",type(b)) a = a - b print("\nThe value of a now is:",a) print("*Updated Data Type of the Variable a is:",type(a))

Output

As we can see from the example above, variable "a" is initially an int, but variable "b" is a float. Following the summing procedure and the storage of the result in variable “a”, the datatype of “a” is automatically changed to float datatype. This is what the implicit type conversion in the Python programming language is.

The Data Type of Variable a is: <class 'int'>
The Data Type of Variable b is: <class 'float'>

The value of a now is: 6.1
*Updated Data Type of the Variable a is: <class 'float'>

Note − The class type of the input parameter is returned by the type() method. Thus, type(9) returns an object of class "int," whereas type("9") returns an object of class "string."

Explicit Type conversions

Users change an object's data type to the one that Explicit Type Conversion demands. Explicit type conversion is performed using predefined functions like int(), float(), and str ().

Typecasting is another name for this conversion process because it involves changing the object's data type by the user.

When a programmer explicitly and precisely specifies a program, the explicit type is converted. For explicit form conversion, Python includes a number of built-in functions.

Note − As we force a given value to a smaller data type via explicit type conversion, data loss may happen. For instance, rounding the decimal places in the output when converting a float value to an int.

Syntax

Following is the syntax of exolicit type conversions −

(required data type)(expression)

Example

Following is an example of explicit type conversion −

a = 47 b = "51" result1 = a + b b = int(b) result2 = a + b print(result2)

Output

The data type of variable “a” is a number, and variable “b” is a string. A TypeError occurs as shown in the output if these two entries are added and the value is kept in the result1 variable.

So, in order to complete this process, we must employ explicit casting.“a” and “b” have been added after “b” was converted to an int. The output displays 400 and the amount is kept in the result2 variable

Traceback (most recent call last):
   File "main.py", line 3, in <module>
      result1 = a + b
TypeError: unsupported operand type(s) for +: 'int' and 'str'

Let's use a simple example to clarify each explicit conversion function type that Python offers.

Int()

Any data type can be converted into an integer data type with this function. The int() function requires 2 parameters, and its syntax is int(variable, base) where "variable" refers to a string and "base" designates the base in which string is located when a string is the data type.

Example

Following is an example of int data type −

a = "58" print("Before conversion the data type of variable a is:",type(a)) number = int(a) print("\nAfter conversion the data type of variable a is:",type(number))

Output

Following is an output of the above code −

Before conversion the data type of variable a is: <class 'str'>

After conversion the data type of variable a is: <class 'int'>

float()

Any data type can be transformed into a float type with this function. Float() has the syntax float(parameter), where parameter is an optional argument. Only an empty float data type variable may be declared when using float without arguments.

Example

Following is an example of float data type −

a = "84" print("Before conversion the data type of variable a is : %s and a value : %s "%(type(a),a)) number = float(a) print("\nAfter conversion the data type of variable a is: %s and number value : %s "%(type(number),number))

Output

Following is an output of the above code −

Before conversion the data type of variable a is : <class 'str'> and a value : 84 

After conversion the data type of variable a is: <class 'float'> and number value : 84.0 

Ord()

Using this function, characters can be changed into integers. This function accepts a single character parameter, ord(character), and transforms it to its corresponding Unicode code value. To determine whether a string contains a special character(like emojis), use this function. Only one character may be used with this function.

Example

Following is an example of ord data type −

char = "H" unicode_character = ord(char) print("\nThe Unicode of the character %s is %s "%(char,unicode_character))

Output

Following is an output of the above code

The Unicode of the character H is 72 

Hex()

To convert numbers to hexadecimal, use this function. The return value of this function, which accepts a single integer or float parameter, is hexadecimal. The hex() function's syntax is hex (parameter).

Example

Following is an example of hex data type −

x = 87 y = hex(x) print(y, "is of the type", type(y))

Output

Following is an output of the above code −

0x57 is of the type <class 'str'>

Oct()

Integers are converted to octal using this function. The return value of this function, which only accepts integer data types as arguments, is an octal value. Oct’s function syntax is oct(argument).

Example

Following is an example of oct data type −

x = 38 y = oct(x) print(y, "is of the type", type(y))

Output

Following is an output of the above code −

0o46 is of the type <class 'str'>

Tuple()

This function is used to create a tuple out of the value. Multiple items can be stored in a variable by using tuples. The tuple() method has the syntax of tuple(argument), and the elements of the tuple are ("one," "two," and "three"). A collection of unchangeable, ordered values is known as a "tuple" (i.e immutable).

Example

Following is an example of tuple data type

x = 'TutorialsPoint' print(tuple(x))

Output

Following is an output of the above code −

('T', 'u', 't', 'o', 'r', 'i', 'a', 'l', 's', 'P', 'o', 'i', 'n', 't')

Set()

After converting to a set, this function returns the type. It’s syntax is set(iterable); providing parameters is not required. Sets are not ordered. {Value 1, Value 2, Value 3, Value 4, and so on} indicate a set.

Example

Following is an example of set data type

x = 'TutorialsPoint' print(set(x))

Output

Following is an output of the above code −

{'r', 'a', 'i', 'o', 's', 'n', 't', 'u', 'T', 'l', 'P'}

List()

This function creates a list object by converting any data type to a list type. Lists are changeable and ordered. list() has the syntax list(parameter), and a list is denoted by [‘one’, 2, ‘three’]. The parameter may be a sequence (string, tuples), collection (set, dictionary), or iterator object, and it is optional.

Example

Following is an example of list data type −

x = 'TutorialsPoint' print(list(x))

Output

Following is an output of the above code

['T', 'u', 't', 'o', 'r', 'i', 'a', 'l', 's', 'P', 'o', 'i', 'n', 't']

Str()

It is used to turn an integer into a string. When combining values of various data types with string data type values, this function is typically employed. The str() function's syntax is str(parameter).

Example

Following is an example of str data type −

x = 39 y = 489.28 z = complex(39,4) print(str(x)) print(str(y)) print(str(z))

Output

Following is an output of the above code −

39
489.28
(39+4j)

Dict()

A dictionary is created with this method from a tuple of order (key, value) values. A dictionary is created by a constructructor dict(). This indicates that if no arguments are supplied, an empty dictionary is created. Its syntax is dict(parameter), where parameter is an optional argument. It creates an empty dictionary object if the parameter is not provided, and it turns the parameter into a dictionary format if it is given.

Example

Following is an example of dict data type −

x = (('s', 6), ('a', 3), ('r', 5), ('i', 8), ('k', 1)) print(dict(x))

Output

Following is an output of the above code −

{'s': 6, 'a': 3, 'r': 5, 'i': 8, 'k': 1}

Chr()

This function converts numbers to their ASCII character equivalents. The syntax for the chr() function is chr(number) and an integer is required. Also, if you pass an out-of-range integer, the method will return a ValueError.

Example

Following is an example of chr data type −

x = 437 y = 57 print(chr(x), "type is", type(chr(x))) print(chr(y), "type is", type(chr(y)))

Output

Following is an output of the above code −

Ƶ type is <class 'str'>
9 type is <class 'str'>

Advertisements