python不同数据类型间的转换
- 字符串与数字之间的转换:
字符串转为数字,要求字符串必须是由纯数字组成的字符串;数字转为字符串则无要求。
字符串与数字之间的转换函数:
原始类型 | 目标类型 | 函数 | 示例 |
---|---|---|---|
整型 | 字符串 | str | new_str = str(123456) |
浮点型 | 字符串 | str | new_str = str(1.23) |
字符串 | 整型 | int | new_int = int(‘123’) |
字符串 | 浮点型 | float | new_float = float(‘1.23’) |
- 字符串与列表之间的转换:
通过 split
函数将字符串转换为列表;通过 join
函数将列表转换为字符串。
split
函数的功能是将字符串按一定规则将字符串切割,并转换成列表。
用法:str.split(sep=None, maxsplit=-1)
,参数 sep
表示切割的规则符号,默认为空格;maxsplit
根据切割符号切割的次数,默认为 -1,表示无限制。示例:
>>> person = 'my name is xiaobai'
>>> person_list = person.split()
>>> person_list
['my', 'name', 'is', 'xiaobai']
join
函数的功能是将列表按一定规则转换成字符串。
用法:sep.join(iterable)
,参数 sep
表示生成字符串用来分割列表每个元素的符号;iterable
表示非数字类型的列表、元组或集合。示例:
>>> person_list
['my', 'name', 'is', 'xiaobai']
>>> person = ' '.join(person_list)
>>> person
'my name is xiaobai'
- 字符串与比特(bytes)之间的转换:
比特(bytes)是二进制的数据流,是一种特殊的字符串,在字符串前用 b
标记。示例:
>>> bt = b'my name is xiaobai'
>>> type(bt)
<class 'bytes'>
比特(bytes)中只能包含 ascii 字符。
通过 encode
函数将字符串转换为比特(bytes);通过 decode
函数将比特(bytes)转换为字符串。
decode
函数的功能是将比特类型转换成字符串。
用法:bytes.decode(encoding='utf-8', errors='strict')
,参数 encoding
表示转换成的编码格式,如 ascii gbk,默认是 utf-8;errors
表示出错时的处理方法,默认是 strict
,表示抛出错误,也可以设置 ignore
忽略错误。示例:
>>> person = 'my name is xiaobai'
>>> person_bt = person.encode('utf-8')
>>> person_bt
b'my name is xiaobai'
- 列表、元组、集合间的转换:
列表、元组、集合间的转换函数:
原始类型 | 目标类型 | 函数 | 示例 |
---|---|---|---|
列表 | 集合 | set | new_set = set([1, 2, 3, 4, 5, 6]) |
列表 | 元组 | tuple | new_tuple = tuple([1, 2, 3, 4, 5, 6]) |
元组 | 集合 | set | new_set = set((1, 2, 3, 4, 5, 6)) |
元组 | 列表 | list | new_list = list((1, 2, 3, 4, 5, 6)) |
集合 | 列表 | list | new_list = list({1, 2, 3, 4, 5, 6}) |
集合 | 元组 | tuple | new_tuple = tuple({1, 2, 3, 4, 5, 6}) |