什么是类型转换,为何做类型转换
将自身数据类型变成新的数据类型,并拥有新的数据类型的所有功能的过程即为类型转换。
为方便更好的帮助处理业务,将类型变更为更为更合适业务场景的类型。
字符串与数字间的转换
如果str类型的数字有小数点,需要先转成float类型后才能再转换成int类型
#整型-->字符串
number = 1234
new_str = str(number)
print(type(new_str)) #<class 'str'>
#浮点型-->字符串
f = 3.14
new_str = str(f)
print(type(new_str)) #<class 'str'>
#字符串-->整型和浮点类型
str_n = '123'
str_f = '3.14'
new_int = int(str_n)
new_f = float(str_f)
print(type(new_int),type(new_f)) #<class 'int'> <class 'float'>
字符串与列表间的转换
- split函数
将字符串以一定规则切割转成列表
用法:string.split(sep=None,maxsplit=-1)
sep:切割的规则符号,不填写,默认空格,如字符串无空格则不分割生成列表
maxsplit:根据切割符号切割的次数,默认-1无限制
info = 'my name is shaishai'
new_info = info.split()
print(new_info) #['my', 'name', 'is', 'shaishai']
a = 'abc'
a = a.split()
print(a) #['abc']
b = 'a,b,c'
b = b.split(',')
print(b) #['a', 'b', 'c']
c = 'a|b|c|d'
c = c.split('|', 1)
print(c) #['a', 'b|c|d']
- join函数
将列表以一定规则转成字符串
用法:sep.join(iterable)
sep:生成字符串用来分割列表每个元素的符号
iterable:非数字类型的列表或元组或集合
info = ['my', 'name', 'is', 'shaishai']
str_info = ' '.join(info)
print(str_info) #my name is shaishai
a = ['a','b','c']
a = '~'.join(a)
print(a) #a~b~c
b = ('a','b','c')
b = ''.join(b)
print(b) #abc
字符串与bytes的转换
- encode和decode函数
将字符串互相转比特(bytes)类型
用法:string.encode(encoding = ‘utf-8’,errors='strict)
bytes.decode(encoding = ‘utf-8’,errors='strict)
encoding:转换成的编码格式,如ascii,gbk,默认utf-8
errors:出错时的处理方法,默认strict,直接抛错误,也可以选择ignore忽略错误
info = 'my name is shaishai'
byte_info = info.encode()
print(type(byte_info),byte_info) #<class 'bytes'> b'my name is shaishai'
str_info= byte_info.decode()
print(type(str_info),str_info) #<class 'str'> my name is shaishai
元组,列表,集合间的转换