Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python3 Data Type Conversion

Python3 Data Type Conversion

Sometimes we need to convert built-in data types; in general you only need to use the data type as a function name.

Python data type conversion can be divided into two kinds:

Implicit type conversion

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

In the following example we perform an operation on data of two different types; the lower data type (integer) is converted to the higher data type (floating-point) to avoid data loss.

Example

num_int

=

123

num_flo

=

1.23

num_new

=

num_int + num_flo

print

(

"The data type of num_int is:"

,

type

(

num_int

)

)

print

(

"The data type of num_flo is:"

,

type

(

num_flo

)

)

print

(

"The value of num_new is:"

,

num_new

)

print

(

"The data type of num_new is:"

,

type

(

num_new

)

)

The output of the above example is:

num_int 数据类型为: 
num_flo 数据类型为: 
num_new: 值为: 124.23
num_new 数据类型为: 

Code analysis:

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

Example

num_int

=

123

num_str

=

"456"

print

(

"The data type of num_int is:"

,

type

(

num_int

)

)

print

(

"The data type of num_str is:"

,

type

(

num_str

)

)

print

(

num_int+num_str

)

The output of the above example is:

num_int 数据类型为: 
num_str 数据类型为: 
Traceback (most recent call last):
  File "/runoob-test/test.py", line 7, in 
    print(num_int+num_str)
TypeError: unsupported operand type(s) for +: 'int' and 'str'

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

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

Explicit type conversion

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

int() forces conversion to an integer:

Example

x

=

int

(

1

)

 

x outputs 1

y

=

int

(

2.8

)

y outputs 2

z

=

int

(

"3"

)

z outputs 3

float() forces conversion to a floating-point number:

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() forces conversion to a string type:

Example

x

=

str

(

"s1"

)

x outputs 's1'

y

=

str

(

2

)

   

y outputs '2'

z

=

str

(

3.0

)

 

z outputs '3.0'

Operations between integers and strings can be done using forced type conversion:

Example

num_int

=

123

num_str

=

"456"

print

(

"The data type of num_int is:"

,

type

(

num_int

)

)

print

(

"Before type conversion, the data type of num_str is:"

,

type

(

num_str

)

)

num_str

=

int

(

num_str

)

   

Force conversion to an integer

print

(

"After type conversion, the data type of num_str is:"

,

type

(

num_str

)

)

num_sum

=

num_int + num_str

print

(

"The result of adding num_int and num_str is:"

,

num_sum

)

print

(

"The data type of sum is:"

,

type

(

num_sum

)

)

The output of the above example is:

num_int 数据类型为: 
类型转换前,num_str 数据类型为: 
类型转换后,num_str 数据类型为: 
num_int 与 num_str 相加结果为: 579
sum 数据类型为: 

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

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