Python3 Data Type Conversion

Sometimes, we need to convert the built-in types of data. For data type conversion, in general, you only need to use the data type as the function name.

Python data type conversion can be divided into two types:

  • Implicit type conversion - done automatically
  • Explicit type conversion - requires the use of type functions to convert

Implicit Type Conversion

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

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

Example

num_int = 123
num_flo = 1.23

num_new = num_int + num_flo

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

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

The output of the above example is:

num_int 数据类型为: <class 'int'>
num_flo 数据类型为: <class 'float'>
num_new: 值为: 124.23
num_new 数据类型为: <class 'float'>

Code analysis:

  • In the example, we have two variables of different data typesnum_intandnum_floperform addition, and store in the variablenum_new.
  • Then we check the data types of the three variables.
  • In the output, we seenum_intYes整型(integer) , num_floYes 浮点型(float)。
  • Similarly, the new variablenum_newYes 浮点型(float), this is because Python converts the lower data type to the higher data type to avoid data loss.

Let's look at another example, adding integer data and string type data:

Example

num_int = 123
num_str = "456"

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

print(num_int+num_str)

The output of the above example is:

num_int 数据类型为: <class 'int'>
num_str 数据类型为: <class 'str'>
Traceback (most recent call last):
  File "/example-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, the operation between integer and string types will result in an error, outputting TypeError. Python cannot use implicit conversion in this case.

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

Explicit Type Conversion

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

int()Converting to integer type:

Example

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

float()Converting to floating point type:

Example

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()Converting to string type:

Example

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

To perform an operation between integer and string types, you can use forced type conversion to complete it:

Example

num_int = 123
num_str = "456"

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

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

num_sum = num_int + num_str

print("The result of adding num_int and num_str is:",num_sum)
print("sum data type is:",type(num_sum))

The output of the above example is:

num_int 数据类型为: <class 'int'>
类型转换前,num_str 数据类型为: <class 'str'>
类型转换后,num_str 数据类型为: <class 'int'>
num_int 与 num_str 相加结果为: 579
sum 数据类型为: <class 'int'>

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

FunctionDescription

int(x [,base])

Convert x to an integer

float(x)

Convert x to a floating point number

complex(real [,imag])

Create a complex number

str(x)

Convert object x to a string

repr(x)

Convert object x to an expression string

eval(str)

Used to evaluate a valid Python expression in a string and return an object

tuple(s)

Convert sequence s to a tuple

list(s)

Convert sequence s to a list

set(s)

Convert to a mutable set

dict(d)

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

frozenset(s)

Convert to an immutable set

chr(x)

Convert an integer to a character

ord(x)

Convert a character to its integer value

hex(x)

Convert an integer to a hexadecimal string

oct(x)

Convert an integer to an octal string

bool(x)

Convert object x to a boolean value (True or False)

bytes([source[, encoding[, errors]]])

Convert an object to an immutable byte sequence

bytearray([source[, encoding[, errors]]])

Convert an object to a mutable byte array

memoryview(obj)

Return a memory view object for the given argument (without copying data)

bin(x)

Convert an integer to a binary string

ascii(x)

Return the ASCII representation of an object, with non-ASCII characters escaped

Other extensions