Python3 数据类型转换
隐式转换与显式转换、数值与字符串互转、序列互转、字符编码与进制转换。
隐式类型转换
Python only auto-promotes in numeric arithmetic: int with float yields float, int with complex yields complex. Strings and numbers are never converted implicitly.
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)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.
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)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.
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)]))['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.
print(ord('A'), ord('中'))
print(chr(65), chr(20013))
b = "中".encode('utf-8')
print(b, len(b))
print(b.decode('utf-8'), len("中"))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.
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}")0b1010 0o12 0xff
10 255
11111111 ff
0b1010隐式类型转换
Python 只在数值运算时自动做「向上提升」:int 与 float 运算得 float,int 与 complex 运算得 complex。字符串和数字不会自动互转。
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)float
complex
complex
TypeError: can only concatenate str (not "int") to str显式类型转换
用内置函数强制转换:int() 截断取整、float() 转浮点、complex() 转复数、str() 转字符串。字符串转数字时内容必须合法,否则 ValueError。
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)3 -3 42
3.14 2.0
(1+2j) 123
ValueError: invalid literal for int() with base 10: '3.14'序列类型互转
list() / tuple() / set() 接受任何可迭代对象,互相转换很方便:列表转集合顺带去重,集合转列表后再 sorted() 就有序了。
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)]))['a', 'b', 'c']
(1, 2)
[1, 2, 3]
['a', 'b']
[('a', 1)]
{'a': 1, 'b': 2}字符与编码
ord(c) 取字符的 Unicode 码位,chr(n) 由码位还原字符。这两个函数是理解「字符 vs 字节」的入口:encode() 出字节,decode() 回字符串。
print(ord('A'), ord('中'))
print(chr(65), chr(20013))
b = "中".encode('utf-8')
print(b, len(b))
print(b.decode('utf-8'), len("中"))65 20013
A 中
b'\xe4\xb8\xad' 3
中 1进制转换
bin() 转二进制、oct() 八进制、hex() 十六进制,结果带前缀。int(s, base) 反过来按指定进制解析字符串。
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}")0b1010 0o12 0xff
10 255
11111111 ff
0b1010