python基础数据类型之间的转换
上次我们介绍了python的四种基础数据类型,分别为:int、float、str、bool。这次我们来讲解它们之间如何进行转换。再讲之前,再为大家介绍两种数据类型:complex与None。
complex 复数类型
# complex 复数
a = 1 + 2j
print(a.real)
print(a.imag)
print(type(a))
E:\shujia\python.exe F:\code\day02.py
1.0
2.0
<class 'complex'>
Process finished with exit code 0
None 空
#None 空
b = None
print(type(b))
E:\shujia\python.exe F:\code\day02.py
<class 'NoneType'>
Process finished with exit code 0
a = 1
b = 0
c = -1
d = -0
e = 1.1
f = 1.0
g = 0.0
h = -0.0
i = -2.1
j = "1"
k = '1.0'
l = '1.2'
m = "True"
n = "False"
o = "0"
p = True
q = False
int转其他类型
int转float
#int转float
print(float(a),float(b),float(c),float(d))
E:\shujia\python.exe F:\code\day02.py
1.0 0.0 -1.0 0.0
Process finished with exit code 0
int转str
#int转str
print(str(a),str(b),str(c),str(d))
E:\shujia\python.exe F:\code\day02.py
1 0 -1 0
Process finished with exit code 0
int转bool
#int转bool 非0即true
print(bool(a),bool(b),bool(c),bool(d),bool(2))
E:\shujia\python.exe F:\code\day02.py
True False True False True
Process finished with exit code 0
float转其他类型
float转int
#float转int
print(int(e),int(f),int(g),int(h),int(i),int(3.9))
E:\shujia\python.exe F:\code\day02.py
1 1 0 0 -2 3
Process finished with exit code 0
这里float转int只取小数点前面的数字,不会四舍五入。
float转str
#float转str
print(str(e),str(f),str(g),str(h),str(i))
E:\shujia\python.exe F:\code\day02.py
1.1 1.0 0.0 -0.0 -2.1
Process finished with exit code 0
float转bool
#float转bool
print(bool(e),bool(f),bool(g),bool(h),bool(i))
E:\shujia\python.exe F:\code\day02.py
True True False False True
Process finished with exit code 0
str转其他类型
str转int
# str转int
# float样式的str值不能转换为int类型 样例:print(int(k))
# 只有整数数值型的字符串才能转换为int
print(int(j), int(o))
E:\shujia\python.exe F:\code\day02.py
1 0
Process finished with exit code 0
str转int型,float样式的 str值不能转换为int类型,且只有整数数值型的字符串可以转换为int。
str转float
# str转float
# 只有数值型的字符串才能转换为float
print(float(j),float(k),float(l),float(o))
E:\shujia\python.exe F:\code\day02.py
1.0 1.0 1.2 0.0
Process finished with exit code 0
只有数值型的字符串才能转换为float。
str转bool
# str转bool
# 只有字符串里为空时,转换为bool类型才为False
print(bool(j),bool(k),bool(l),bool(m),bool(n),bool(o),bool(" "),bool(""))
E:\shujia\python.exe F:\code\day02.py
True True True True True True True False
Process finished with exit code 0
只有字符串里为空时,转换为bool类型才为False,其余都为True.
bool转其他类型
bool转int
# bool转int
print(int(p),int(q))
E:\shujia\python.exe F:\code\day02.py
1 0
Process finished with exit code 0
bool转float
# bool转float
print(float(p),float(q))
E:\shujia\python.exe F:\code\day02.py
1.0 0.0
Process finished with exit code 0
bool转str
# bool转str
print(str(p),str(q))
E:\shujia\python.exe F:\code\day02.py
True False
Process finished with exit code 0