Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Different Data Conversion Methods in Python



Data conversion in Python refers to changing the data type of a value to another data type. Python supports two different types of data conversion, such as Implicit conversion and explicit conversion.

  • Implicit Conversion is performed by the Python interpreter automatically.
  • Explicit Conversion is manually done by the programmer using built-in functions in Python

Implicit Conversion

Python automatically converts one data type to another, and this type of conversion is called Implicit conversion. To avoid any data loss during runtime, the smaller data type is converted into a higher data type.

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 which shows how to convert one datatype to another using Implicit Conversion -

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("\n Now the value of 'a' is:",a)
print("*Updated Data Type of the Variable 'a' is:",type(a))

As we can see from the above example, the variable "a" is initially an int, and the variable "b" is a float. If you see the output, you can observe that the datatype of "a" is automatically changed to float. 

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

 Now the value of 'a' 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 conversion

Explicit conversion is also known as Type casting, in which the programmer uses predefined functions in Python to convert one data type to another.

When a programmer explicitly and precisely specifies a program, then 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 conversion, data loss may happen. For example, rounding the decimal values, i.e., a float value to an int, then the decimal places will be lost.

Syntax

Following is the syntax of Exolicit conversion in Python -

(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)

In the above program, the data type of variable "a" is an int, 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'

Common Conversion Functions

Following are the common conversion functions available in Python -

  • int(x): Converts x to an integer
  • float(x): Converts x to a floating-point number
  • str(x): Converts x to a string
  • list(x): Converts x to a list
  • tuple(x): Converts x to a tuple
  • set(x): Converts x to a set
  • dict(x): Converts x (a sequence of key-value pairs) to a dictionary
  • bool(x): Converts x to a Boolean

String to Integer Conversion using int()

Any data type can be converted into an integer data type with the int() 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 the string is located when a string is the data type.

Example

Following is an example of converting the string to an nbsp;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))

Following is an output of the above program -

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

String to Float Conversion using float()

The float() function in Python is used to convert any data type into a float type. 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 which converts the string datatype to float data type using float() function -

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))

Following is an output of the above program -

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 

Character to Unicode Conversion using ord()

The ord() function in Python is used to convert a character into its corresponding Unicode code point. The ord() function accepts a single character as an argument. It is useful to find the Unicode integer representation of characters, such as special characters and emojis.

Example

Below is an example that converts a character to its Unicode code point using the ord() function -

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

Following is an output of the above example -

The Unicode of the character 'H' is 72 

Number to Hexadecimal Conversion using hex()

The hex() function in Python is used to convert an integer number into its corresponding hexadecimal string representation. The hex() function accepts an integer or a float and is usually used with integers and returns a hexadecimal string prefixed with 0x.

Example

Below is an example that converts a number to hexadecimal using the hex() function -

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

Here is an output of the above example -

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

Number to Octal Conversion using oct()

The oct() function in Python is used to convert an integer number into its corresponding octal string representation. The oct() function accepts only integer values and returns a string that represents the octal value which prefixed with 0o.

Example

Following is an example which converts a number to octal using the oct() function -

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

Below is an output of the above example -

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

String to Tuple Conversion using tuple()

The tuple() function in Python is used to convert an iterable, such as a string or list, into a tuple. A tuple is a collection of ordered and immutable elements. The tuple() function has the syntax tuple(iterable) and returns a new tuple containing the elements of the iterable.

Example

Here is an example that converts a string into a tuple using the tuple() function -

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

Below is an output of the above program -

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

String to Set Conversion using set()

The set() function in Python is used to convert an iterable into a set. A set is an unordered collection of unique elements. The syntax of this function is set(iterable). When converting a string into a set, it returns a set of unique characters from that string.

Example

Below is an example that converts a string into a set using the set() function -

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

Following is an output of the above example -

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

String to List Conversion using list()

The list() function in Python is used to convert iterables into a list. A list is an ordered and mutable sequence of items. The syntax of this function is list(iterable). It accepts strings, tuples, sets, or even dictionaries (iterating over keys).

Example

Here is an example that converts a string into a list using the list() function -

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

Following is an output of the above program -

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

Integer to String Conversion using str()

The str() function is used to convert different data types, such as integers, floats, or complex numbers, into their string representation. This is especially helpful when concatenating numbers with strings. The syntax of this function is

str(parameter)

Example

Here is an example of converting an Integer to a string datatype using str() function -

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

print(str(x))
print(str(y))
print(str(z))

Here is the output of the above program -

39
489.28
(39+4j)

ASCII Conversion using chr()

The chr() function returns the character that represents the specified Unicode code point. The input should be an integer in the valid Unicode range. If the number is outside the range, then a ValueError is raised. The syntax of the chr() function is -

chr(number)

Example

In this example, we will see how to convert the ASCII value to character datatype using the chr() function -

x = 437
y = 57

print(chr(x), "type is", type(chr(x)))
print(chr(y), "type is", type(chr(y)))

Following is the output of the above program -

? type is 
9 type is 
Updated on: 2025-06-09T10:17:08+05:30

772 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements