Python3 数据类型转换

隐式转换与显式转换、数值与字符串互转、序列互转、字符编码与进制转换。

Beginner
Key Points只有数值之间会自动提升;其余都要显式转换。int() 截断不四舍五入,str 转数字失败会抛 ValueError。

隐式类型转换

Python only auto-promotes in numeric arithmetic: int with float yields float, int with complex yields complex. Strings and numbers are never converted implicitly.

Python
print(type(1 + 1.0).__name__)
print(type(1 + 1j).__name__)
print(type(1 + 1.0 + 1j).__name__)

try:
    print("a" + 1)
except TypeError as e:
    print("TypeError:", e)
Output
float
complex
complex
TypeError: can only concatenate str (not "int") to str

显式类型转换

Coerce with built-ins: int() truncates, float() converts to float, complex() to complex, str() to string. Converting a string to a number requires valid content, otherwise ValueError.

Python
print(int(3.9), int(-3.9), int("42"))
print(float("3.14"), float(2))
print(complex(1, 2), str(123))

try:
    int("3.14")
except ValueError as e:
    print("ValueError:", e)
Output
3 -3 42
3.14 2.0
(1+2j) 123
ValueError: invalid literal for int() with base 10: '3.14'

序列类型互转

list(), tuple() and set() accept any iterable, so conversion is trivial: list to set deduplicates, and set to list plus sorted() gives order back.

Python
print(list("abc"))
print(tuple([1, 2]))
print(sorted(set([3, 1, 3, 2])))

print(list({'a': 1, 'b': 2}))
print(list({'a': 1}.items()))
print(dict([('a', 1), ('b', 2)]))
Output
['a', 'b', 'c']
(1, 2)
[1, 2, 3]
['a', 'b']
[('a', 1)]
{'a': 1, 'b': 2}

字符与编码

ord(c) returns a character's code point and chr(n) turns it back. They are the entry point to understanding characters versus bytes: encode() produces bytes, decode() restores text.

Python
print(ord('A'), ord('中'))
print(chr(65), chr(20013))

b = "中".encode('utf-8')
print(b, len(b))
print(b.decode('utf-8'), len("中"))
Output
65 20013
A 中
b'\xe4\xb8\xad' 3
中 1

进制转换

bin(), oct() and hex() convert to base 2, 8 and 16 with a prefix. int(s, base) parses a string in the given base back to an integer.

Python
print(bin(10), oct(10), hex(255))
print(int('1010', 2), int('ff', 16))
print(format(255, 'b'), format(255, 'x'))
print(f"{10:#06b}")
Output
0b1010 0o12 0xff
10 255
11111111 ff
0b1010

Friends & Partners