Python数据转换(一)

来源:互联网 发布:砾石网软件 编辑:程序博客网 时间:2024/06/05 16:58

int(x,base)

#int(x,base)表示将base下的x转换为十进制的数值;默认base为10,也就是说默认x都是十进制的数据;a='10';print(a);#查看a的数据类型;print('a的类型是',end=''),print(type(a)),#表示将十进制数a转换为十进制;b = int(a);print(b);print('b的类型是',type(b));#表示将二进制数a,转换为十进制数据;c = int(a,2);print(c);print('c的类型是',type(c));
输出
10a的类型是<class 'str'>10b的类型是 <class 'int'>2c的类型是 <class 'int'>



float(x)
#float(x) 将x转为float类型;d='1.1';print('d的类型是',type(d));f = float(d);print(f);print('f的类型是',type(f));

输出
d的类型是 <class 'str'>1.1f的类型是 <class 'float'>


complex(real[,imag])

#complex(real[,imag])创建一个复数;创建一个值为real + imag * j的复数或者转化一个字符串或数为复数。如果第一个参数为字符串,则不需要指定第二个参数。#参数real: int, long, float或字符串;#参数imag: int, long, float。e1 = complex(3,2);print(e1);print('e1的类型是',type(e1));e2 = complex('2');print(e2);e3 = complex('1+2j');print(e3);

输出

(3+2j)e1的类型是 <class 'complex'>(2+0j)(1+2j)



repr(str)

#str(x),将x转换为字符串g = 1;print('g的类型是',type(g));print(str(g));print('str(g)的类型是',str(g));#repr(str)将对象 x 转换为表达式字符串。list =[1,'a'];print(repr(list));print('repr(list)的类型是',type(repr(list)));#str()与repr()区别:str是将所有值转换为字符串,相当tostring(),而repr则是相当于编译器,转换后的内容是给编译器看的print(str('你好'));print(repr('你好'));print(str('hello\n换行了'));#输出两行print(repr('hello\n换行了'));


输出

g的类型是 <class 'int'>1str(g)的类型是 1[1, 'a']repr(list)的类型是 <class 'str'>你好'你好'hello换行了'hello\n换行了'


eval(str)

#eval(str)函数将字符串str当成有效Python表达式来求值,并返回计算结果。a = "[[1,2], [3,4], [5,6], [7,8], [9,0]]"print('a的类型',type(a));b = eval(a);print(b);print(type(b));c=1;print(eval('c+1'));


输出

a的类型 <class 'str'>[[1, 2], [3, 4], [5, 6], [7, 8], [9, 0]]<class 'list'>2


原创粉丝点击