使用python处理数据时,不可避免的要进行数据类型之间的转换,诸如整型和字符串之间的转换。
转换有隐式和显式转换,隐式也称自动转换,不用做特殊。显示转换,也称为数据类型的强制类型转换,通过内置函数实现。
7.1 转为整型
通过内置函数int(x [,base]),可把x值转为整数。其中base是进制,默认是10进制。
# 浮点数转为整型,截断小数点f = 99.5to = int(f)print(to)# 布尔转为整型b = Trueto = int(b)print(to)# 字符串转为整型s = "520"to = int(s)print(to)# 转为16进制print(int(s, base=16))
转换是不是都会成功?--不一定,像字符串内容,比如“酷”,就没办法转成整数。有时候扮酷,是需要付出代价的。
# 非数字内容s = "酷"# 转换为整数,报错to = int(s)print(to)
既然有异常,那得处理。可在转换前,通过isdigit()函数判断字符串内容是否全是数字,是才转换,不是的话,做其他处理。这里提前剧透条件语句。
# 非数字内容s = "酷"if s.isdigit(): to = int(s) print(to)else: print("做其他处理。")
7.2 转为浮点型
通过float(x),把x值转为浮点型。
# 整型转为浮点数i = 99to = float(i)print(to)# 字符串转为浮点数s = "520.00"to = float(s)print(to)
字符串转为浮点数的过程中,也存在不成功的情况。可惜Python没有直接的函数,可以判断是否为浮点数,得通过数据类型进行判断。获取类型的函数,之前已知悉,用type(),判断是否某种类型,使用 is。 判断字符串是否是浮点数,语法是: if type(eval(str)) is float: 。其中eval取得字符串串表达式内容。
# 字符串内容s = "13.14"if type(eval(s)) is float: f = float(s) print(f)else: print("其他处理。")
7.3 转为布尔型
在Python里,整型、浮点型、字符串都可以转为布尔类型。除了0为False,其他的全为True。其中字符串记得用eval()取得表达式,否则"0"返回的是True。因为“0”不是0。
# 整型转为布尔i = 0to = bool(i)print(to)# 浮点数转为布尔f = 99.2to = bool(f)print(to)# 字符串转为布尔s = "0"to = bool(eval(s))print(to)
7.4 转为字符串
通过str(x)函数把x内容,转为字符串,x是指定对象,包括整型、浮点数、数组等等。
# 整型转为字符串i = 102to = str(i)print(to)# 浮点数转为字符串f = 36.6to = str(f)print(to)# 布尔转为字符串b = 0to = str(b)print(to)# 数组转为字符串array = ["101