类型转换
常用的类型转换内置函数:
| 函数 | 说明 | 示例 |
|---|---|---|
int(x[, base]) | 转整数,字符串可按进制解析 | int('ff', 16) → 255 |
float(x) | 转浮点数 | float('3.14') → 3.14 |
str(x) | 转字符串 | str(42) → '42' |
bool(x) | 转布尔值,0、''、[]、None 等为 False | bool('') → False |
list(iterable) | 转列表 | list('abc') → ['a', 'b', 'c'] |
tuple(iterable) | 转元组 | tuple([1, 2]) → (1, 2) |
dict(...) | 转字典(键值对序列或关键字参数) | dict(a=1, b=2) → {'a': 1, 'b': 2} |
set(iterable) | 转集合,自动去重 | set([1, 2, 2]) → {1, 2} |
bytes(x) | 转字节串 | bytes('hi', 'utf-8') → b'hi' |
ord(c) | 单字符转 Unicode 码点 | ord('A') → 65 |
chr(i) | Unicode 码点转字符 | chr(65) → 'A' |
bin / oct / hex | 整数转二 / 八 / 十六进制字符串 | bin(10) → '0b1010' |
示例
print(int('42'), int('ff', 16)) # 42 255
print(float('3.14')) # 3.14
print(str(42) + '!') # 42!
print(bool(''), bool([]), bool(0)) # False False False
print(list('abc')) # ['a', 'b', 'c']
print(tuple([1, 2])) # (1, 2)
print(dict(a=1, b=2)) # {'a': 1, 'b': 2}
print(set([1, 2, 2, 3])) # {1, 2, 3}
print(bytes('hi', 'utf-8')) # b'hi'
print(ord('A'), chr(97)) # 65 a
print(bin(10), oct(10), hex(255)) # 0b1010 0o12 0xff