Skip to content

Python3 Data Type Conversion

Sometimes, we need to convert between built-in data types. In general, you just need to use the data type name as a function.

Python data type conversion can be divided into two types:

  • Implicit Type Conversion - automatic
  • Explicit Type Conversion - requires using type functions to convert

In implicit type conversion, Python automatically converts one data type to another without our intervention.

In the following example, we perform operations on two different types of data. The lower data type (integer) is converted to the higher data type (float) to avoid data loss.

num_int = 123
num_flo = 1.23

num_new = num_int + num_flo

print("num_int data type:",type(num_int))
print("num_flo data type:",type(num_flo))

print("num_new value:",num_new)
print("num_new data type:",type(num_new))

The above example outputs:

num_int data type: <class 'int'>
num_flo data type: <class 'float'>
num_new value: 124.23
num_new data type: <class 'float'>

Code explanation:

  • In the example, we add two variables of different data types, num_int and num_flo, and store the result in the variable num_new.
  • Then we check the data types of the three variables.
  • In the output, we see that num_int is integer, and num_flo is float.
  • Likewise, the new variable num_new is float, because Python converts the smaller data type to the larger data type to avoid data loss.

Let’s look at another example, adding an integer and a string:

num_int = 123
num_str = "456"

print("num_int data type:",type(num_int))
print("num_str data type:",type(num_str))

print(num_int+num_str)

The above example outputs:

num_int data type: <class 'int'>
num_str data type: <class 'str'>
Traceback (most recent call last):
  File "/runoob-test/test.py", line 7, in <module>
    print(num_int+num_str)
TypeError: unsupported operand type(s) for +: 'int' and 'str'

As can be seen from the output, operations between integer and string types result in an error, outputting a TypeError. Python cannot use implicit conversion in this case.

However, Python provides a solution for these situations, called explicit conversion.

In explicit type conversion, the user converts the object’s data type to the desired data type. We use predefined functions such as int(), float(), str(), etc., to perform explicit type conversion.

int() forces conversion to integer:

x = int(1)   # x outputs 1
y = int(2.8) # y outputs 2
z = int("3") # z outputs 3

float() forces conversion to float:

x = float(1)     # x outputs 1.0
y = float(2.8)   # y outputs 2.8
z = float("3")   # z outputs 3.0
w = float("4.2") # w outputs 4.2

str() forces conversion to string:

x = str("s1") # x outputs 's1'
y = str(2)    # y outputs '2'
z = str(3.0)  # z outputs '3.0'

Operations between integer and string types can be accomplished using explicit type conversion:

num_int = 123
num_str = "456"

print("num_int data type:",type(num_int))
print("Before conversion, num_str data type:",type(num_str))

num_str = int(num_str)    # Force conversion to integer
print("After conversion, num_str data type:",type(num_str))

num_sum = num_int + num_str

print("Sum of num_int and num_str:",num_sum)
print("sum data type:",type(num_sum))

The above example outputs:

num_int data type: <class 'int'>
Before conversion, num_str data type: <class 'str'>
After conversion, num_str data type: <class 'int'>
Sum of num_int and num_str: 579
sum data type: <class 'int'>

The following built-in functions can perform conversions between data types. These functions return a new object representing the converted value.

Function Description
int(x [,base]) Converts x to an integer
float(x) Converts x to a floating-point number
complex(real [,imag]) Creates a complex number
str(x) Converts object x to a string
repr(x) Converts object x to an expression string
eval(str) Evaluates a valid Python expression in a string and returns an object
tuple(s) Converts sequence s to a tuple
list(s) Converts sequence s to a list
set(s) Converts to a mutable set
dict(d) Creates a dictionary. d must be a sequence of (key, value) tuples
frozenset(s) Converts to an immutable set
chr(x) Converts an integer to a character
ord(x) Converts a character to its integer value
hex(x) Converts an integer to a hexadecimal string
oct(x) Converts an integer to an octal string
bool(x) Converts object x to a boolean value (True or False)
bytes([source[, encoding[, errors]]]) Converts an object to an immutable byte sequence
bytearray([source[, encoding[, errors]]]) Converts an object to a mutable byte array
memoryview(obj) Returns a memory view object of the given argument (without copying data)
bin(x) Converts an integer to a binary string
ascii(x) Returns the ASCII representation of an object; non-ASCII characters are escaped