概述
python中数据类型包含:int(整型),float(浮点型),boolean(布尔值), String(字符串),List(列表),Tuple (元组),Set(集合),Dictionary(字典),复数。该篇主要针对基础数据类型(int,float,boolean)进行讲解。
算术运算
整数运算
>>> 2 + 2
4
>>> 3 - 2
1
>>> 5 * 2
10
>>> 4 / 2
2.0
>>> 8 / 5
1.6 #2.7版本中为1,3.x版本中为1.6
>>> 2e304 * 39238172739329
inf #infinity(无穷大)
#注意:当计算值过大时,显示inf
浮点数运算
>>> 2.0 + 3
5.0
>>> 2.0 -1
1.0
>>> 2.0 * 2
4.0
>>> 4.0 / 2
2.0
#注意:带浮点数的运算结果总是返回浮点数
混合运算
>>> (45 + 5 - 5*6) / 4
5.0
求模运算%
>>> 17 % 3
2
>>> 5 * 3 + 2 # 商 * 除数 + 余数
17
次方运算
>>> 5 ** 2 # 5的平方
25
>>> 2 ** 7 # 2的7次方
128
>>> -3 ** 2
-9
>>> (-3) ** 2
9
#注意:** 比 -,+ 运算符有更高优先级
取整运算
>>> 17 / 3
5.666666666666667
>>> 17 // 3
5
# 说明:// 运算符返回结果中整数部分
#例子:时间戳换算成 xx天xx小时xx分xx秒
#-*- encoding:utf-8 -*-
#!/usr/bin/env python
timestamp = 1529843808
days = str(timestamp // 86400)
hours = str((timestamp % 86400) // 3600)
minutes = str(((timestamp % 86400) % 3600) // 60)
seconds = str(((timestamp % 86400) % 3600) % 60)
print(days + '天 '+ hours +'小时 '+ minutes + '分 ' + seconds +'秒')
虚数与复数运算
>>> 2 + 3 + 3j #3j虚数
(5+3j)
>>> 2 + (3 + 2j)
(5+2j)
>>> 5j + 5j
10j
#说明:python用j或J后缀来标记复数的虚数部分,如3+5j
布尔常量
Boolean包含两个常量False,True(注意:首字母必须大写,否则报错
>>> True
True
>>> False
False
>>> True == 1
True
>>> False == 0
True
>>> False < 1
True
数据类型转换
字符串数字转为int型数字
>>> string = '1234'
>>> string
'1234'
>>> int(string)
1234
注意:int函数仅对数字型的字符有效
还可以按指定进制转换字符串数字为指定进制的数字
>>> int("12", 16)
int型数字转为字符串类型
>>> str(512)
'512'
int型转浮点型
>>> float(99)
99.0
浮点型转int型
>>> int(99.5)
99
浮点型转字符串类型
>>> str(99.5)
'99.5'
获取字符的ASCII码
>>> ord("A")
65
注意:ord函数只能用于包含单个字符的字符串
将ASCII码转换为字符
>>> chr(65)
'A'
数据类型验证
type(object) # 用于显示object的数据类型
整型
>>> type(1)
<class 'int'>
浮点型
>>> type(1.0)
<class 'float'>
bool型
>>> type(False)
<class 'bool'>
字符串
>>> type('shouke')
<class 'str'>
集合
>>> type({1,2})
<class 'set'>
列表
>>> type([1, 2, 3])
<class 'list'>
元组
>>> type((1, 2, 3))
<class 'tuple'>
字典
>>> type({1:"i", 2:"shouke"})
<class 'dict'>
复数
>>> type(12j + 1)
<class 'complex'>
----------
字符串
>>> type("")
<class 'str'>
元组
>>> type(())
<class 'tuple'>
列表
>>> type([])
<class 'list'>
集合
>>> type(set())
<class 'set'>
字典
>>> type({})
<class 'dict'>
字节
>>> type(b'')
<class 'bytes'>
应用举例
>>> obj = 'string'
>>> if type(obj) != type({}):
... print("type of arg must be 'dict'")
...
type of arg must be 'dict'
转载请注明:XAMPP中文组官网 » Python 基础数据类型讲解