Python数据类型转换
Mar丶流年 人气:01.int,float相互转换
例1:
int转float使用float(int)
float转int使用int(float)
# coding:utf-8: if __name__ == '__main__': a = 1.56 print(int(a)) # 1 b = 1 print(float(b)) # 1.0
2.int,string相互转换
例1:string转int使用int(string)。要求string只能由数字组成,否则报错
int转string使用str(int)
# coding:utf-8: if __name__ == '__main__': a = '123' print(int(a)) # 123 # print(int('123.0')) Error # print(int('a123')) Error b = 123 print(type(str(b))) # <class 'str'>
3.float,string相互转换
例1:float转string使用str(float)
string转float使用float(string)。string只能由数字或数字加一个点构成,否则报错
# coding:utf-8: if __name__ == '__main__': a = 123.0 print(type(str(a))) # <class 'str'> a = '123.01' print(float(a)) # 123.01 # print(float('123.01.1')) Error print(float('.123')) # 0.123 print(float('123.')) # 123.0 print(float('123')) # 123.0
4.string,list相互转换
# coding:utf-8: if __name__ == '__main__': ''' 例1:list(string)能将字符串一个字符一个字符的切割为列表 string.join(list)能将list每一个元素之间以string相拼接形成字符串 例2:string.split(sep=None,max_split = -1) 按照指定字符和切割次数将字符串变成list sep:切割符,默认切空格 max_split:切割次数 默认-1代表无限制,切完为止 ''' # 例1 print(list('abc')) # ['a', 'b', 'c'] print(''.join(['a', 'b', 'c'])) # 'abc' print(','.join(['a', 'b', 'c'])) # 'a,b,c' # 例2 print('a,b,c'.split(',', 1)) # ['a', 'b,c'] print('a,b,c'.split(',')) # ['a', 'b', 'c'] print('a b c'.split()) # ['a', 'b', 'c']
5.string,tuple相互转换
# coding:utf-8: if __name__ == '__main__': ''' 例1:string转tuple使用tuple(string):得到的tuple由字符串的每一个字符构成 tuple不能直接转成string:可以先转list,后转string ''' # 例1 string = '12344' t = tuple(string) print(t) # ('1', '2', '3', '4', '4') print(''.join(list(t))) # '12344'
6.tuple,list相互转换
# coding:utf-8: if __name__ == '__main__': ''' 例1:list转tuple使用tuple(list) tuple转list使用list(tuple) ''' # 例1 a = ['a', 'b', 'c'] t = tuple(a) print(t) # ['a', 'b', 'c'] l = list(t) print(l) # ['a', 'b', 'c']
7.转换成bool类型
# coding:utf-8: if __name__ == '__main__': ''' 例1:None,0,空字符串,空list,空tuple,空dict,空set都能转成False,其它都能转成True ''' # 例1 a = 1 print(bool(a)) # True print(bool(2)) # True print(bool(0)) # False print(bool(None)) # False print(bool([])) # False print(bool([1])) # True print(bool(set())) # False print(bool(set('1'))) # True print(bool({})) # False print(bool({'name': 'xie'})) # True print(bool('')) # False print(bool(' ')) # True print(bool('0')) # True print(bool('False')) # True
8.bool转换其它类型
# coding:utf-8: if __name__ == '__main__': ''' 例1:bool转int:True=>1,False=>0 例2:bool转float:True=>1.0,False=>0.0 例3:bool转string:True=>'True',False=>'False' ''' a = True b = False # 例1 print(int(a)) # 1 print(int(b)) # 0 # 例2 print(float(a)) # 1.0 print(float(b)) # 0.0 # 例3 print(str(a)) # 'True' print(str(b)) # 'False'
加载全部内容