Python基本数据类型
运算符
- 算数运算
- 比较运算
- 赋值运算
- 逻辑运算
- 成员运算
一、算数运算
二、比较运算
三、赋值运算
四、逻辑运算
五、成员运算
基本数据类型
一、数字
int(整形)
在32位机器上,整数的位数为32位,取值范围为-2**31~2**31-1,即-2147483648~2147483647
在64位系统上,整数的位数为64位,取值范围为-2**63~2**63-1,即-9223372036854775808~9223372036854775807
二、布尔值
真或假 True False
1或0
三、字符串
“hello world”
1、常用功能:
- 移除空白
- 分割
- 长度
- 索引
- 切片
2、循环
white循环
1 s = "alex" 2 start = 0 3 while start < len(s): 4 temp = s[start] 5 print(temp) 6 start += 1 7 a 8 l 9 e 10 x
for循环
1 s = "alex" 2 for item in s: 3 print(item) 4 a 5 l 6 e 7 x
for循环中,break和continue同样适用
1 s = "alex" 2 for i in s: 3 if i == "e": 4 continue 5 print(i) 6 a 7 l 8 x
1 s = "alex" 2 for i in s: 3 if i == "e": 4 break 5 print(i) 6 a 7 l
3、内部功能:
##索引
实例:
1 s = "wang" 2 print(s[0]) 3 w 4 print(s[1]) 5 a 6 print(s[2]) 7 n 8 print(s[3]) 9 g
def len(*args, **kwargs): #获取长度
实例:
1 ret = len(s) 2 print(ret) 3 4
##切片
实例:
1 #取字符串中前两个字符 2 # 0=<0,1<2 3 s = "alex" 4 print(s[0:2]) 5 al
def capitalize(self): #首字母变成大写
实例:
1 a1 = "haha" 2 ret = a1.capitalize() 3 print(ret) 4 Haha
def casefold(self): #其效果和 lower() 方法非常相似,都可以转换字符串中所有大写字符为小写。
实例:
1 a1 = "HaHa" 2 ret = a1.casefold() 3 print(ret) 4 haha
def center(self, width, fillchar=None): #内容居中,width:总长度,fillchar:空白处填充内容,默认无
实例:
1 a1 = "hhh" 2 ret = a1.center(20,'_') 3 print(ret) 4 ________hhh_________
def count(self, sub, start=None, end=None): #子序列的个数,也就是某个元素出现的次数,start从哪开始,从哪里截止。
实例:
1 ##a在a1字符串中出现的次数 2 a1 = "alex is alph" 3 ret = a1.count('a') 4 print(ret) 5 2 6 ##a在a1字符串中,从0至5这个区间中出现的次数 7 a1 = "alex is alph" 8 ret = a1.count('a',0,5) 9 print(ret) 10 1
def encode(self, encoding='utf-8', errors='strict'): # 编码,针对Unicode
def decode(self, encoding='utf-8', errors='strict'): #解码
endswith(self, suffix, start=None, end=None): #是否以XX结尾
实例:
1 ##是否以o结尾的 2 temp = "hello" 3 print(temp.endswith('o')) 4 True 5 #字符串里大于0小于2的字符中,是否有以e结尾的 6 print(temp.endswith('e',0,2)) 7 True
expandtabs(self, tabsize=8): #将tab键转换成空格,默认一个tab转换成8个空格
实例:
1 conten = "hello\t999" ##\t 制表符代表tab键 2 print(conten) 3 hello 999 4 #将tab键换成空格,一个tab键是8个空格 5 print(conten.expandtabs()) 6 hello 999 7 #指定转换成20个空格 8 print(conten.expandtabs(20)) 9 hello 999
find(self, sub, start=None, end=None): #寻找子序列的位置,找到了就返回所在的位置,有重复的,只显示找到的第一个的位置,找不到就显示-1
实例:
1 s = "wxx hello" 2 print(s.find("x")) 3 1 4 print(s.find("b")) 5 -1
format(self, *args, **kwargs): #字符串的格式化,动态参数
实例:
1 s = "hello {0},age {1}" 2 print(s) 3 hello {0},age {1} 4 #{0} 占位符,必须是从0开始 5 #format的作用是将传入的参数替换成占位符 6 new1 = s.format('wxq','27') 7 print(new1) 8 hello wxq,age 27
def index(self, sub, start=None, end=None): #子序列的位置,功能同find()找到就返回其位置,如果没有找到,报错
def isalnum(self): # 是否是字母和数字
实例:
1 a = "wxq12" 2 b = a.isalnum() 3 #验证字符串是否只是字母和数字 4 print(b) 5 True
def isalpha(self): # 是否是字母
实例:
1 a = "wxq12" 2 b = a.isalpha() 3 #验证字符串是否只是字母 4 print(b) 5 False
def isdecimal(self): #检查字符串是否只包含十进制字符。这种方法只存在于unicode对象。
实例:
1 str = u"this2009" 2 print(str.isdecimal()) 3 False 4 str = u"2323241245421" 5 print(str.isdecimal()) 6 True
def isdigit(self): # 检查字符串是否只包含数字
实例:
1 a = "12122312" 2 b = a.isdigit() 3 #验证字符串是否只是数字 4 print(b) 5 True
def isidentifier(self): #判断字符串是否是合法的标识符,字符串仅包含中文字符合法,实际上这里判断的是变量名是否合法。
实例:
1 print('3'.isidentifier()) 2 False 3 print('_3'.isidentifier()) 4 True 5 print('3sdf'.isidentifier()) 6 False 7 print('呵呵'.isidentifier()) 8 True
def islower(self): # 验证字符串是否小写
实例:
1 a = "sdjflsdjf" 2 b = a.islower() 3 #验证字符串是否小写 4 print(b) 5 True
def isspace(self): #验证是否空格
实例:
1 a = " " 2 a1 = "s s" 3 b = a.isspace() 4 b1 = a1.isspace() 5 #验证字符串是否是空格 6 print(b) 7 True 8 print(b1) 9 False
def istitle(self): #验证字符串首字母是否是标题(首字母大写)
实例:
1 a = "Sdjf Flsdjf" 2 b = a.istitle() 3 #验证字符串首字母是否是标题(首字母大写) 4 print(b) 5 True
def isupper(self): #验证字符串是否全部是大写
实例:
1 a = "SDFS" 2 b = a.isupper() 3 #验证字符串是否全部是大写 4 print(b) 5 True
def join(self, iterable): #连接,自定义某个字符作为间隔参数,将每个元素连接起来
实例:
1 l1 = ["al","wa"] #列表 2 l2 = ("alex","wang") #元组 3 s1 = "3&!".join(l1) 4 s2 = "^___".join(l2) 5 print(s1) 6 al3&!wa 7 print(s2) 8 alex^___wang
def lower(self): #变成小写
实例:
1 #变成小写 2 aa = "The NAME" 3 print(aa.lower()) 4 the name
def ljust(self, width, fillchar=None): #内容左对齐,指定字符串的长度,并且自定义后面的填充内容
实例:
1 a = "sfs ws sdf" 2 print(a.ljust(20,'&')) 3 sfs ws sdf&&&&&&&&&&
def lstrip(self, chars=None): # 移除左侧的空格
def rstrip(self, chars=None): # 移除右侧的空格
def strip(self, chars=None): # 移除两侧的空格
实例:
1 s = " al ex " 2 #移除左边的空白(空格) 3 news = s.lstrip() 4 print(news) 5 al ex 6 #移除右边的空白(空格) 7 news = s.rstrip() 8 print(news) 9 al ex 10 #移除两边的空白(空格),如果中间有空格则无法去除 11 news = s.strip() 12 print(news) 13 al ex
def partition(self, sep): #分割,前,中,后三部分,从左向右查找,将设定的字符串分割成元组
实例:
1 s = "alex SB alst haha" 2 ret = s.partition('SB') 3 #将设定的字符串分割成元组 4 #('alex ', 'SB', ' alst') 5 print(ret) 6 ('alex ', 'SB', ' alst haha')
def replace(self, old, new, count=None): #替换
实例:
1 s = "alex SB alst SDFal" 2 ret = s.replace("al","BB") 3 #从左往右匹配al,替换成BB,第三个参数是指要替换前几次出现的次数 4 ret1 = s.replace("al","BB",2) 5 print(ret) 6 BBex SB BBst SDFBB 7 print(ret1) 8 BBex SB BBst SDFal
def rfind(self, sub, start=None, end=None): #从右向左查找字符串中的字符
实例:
1 #rfind的功能是从右向左查找字符串中的字符 2 s = "wxq hq" 3 #找到了就返回出所在的位置,如果有重复的,只显示找到的第一个的位置,找不到就显示-1 4 print(s.rfind("q")) 5 5 6 print(s.rfind("b")) 7 -1
def rindex(self, sub, start=None, end=None): #从右向左查找子序列的位置,功能同rfind()找到就返回其位置,如果没有找到,报错
def rjust(self, width, fillchar=None): #内容右对齐,指定字符串的长度,并且自定义左侧的填充内容
实例:
1 # #内容右对齐,指定字符串的长度,并且自定义左侧的填充内容 2 a = "sfs ws sdf" 3 print(a.rjust(20,'&')) 4 &&&&&&&&&&sfs ws sdf
def rpartition(self, sep): #分割,前,中,后三部分,从左向右查找,将设定的字符串分割成元组
实例:
1 #从右向左查找,将设定的字符串分割成元组 2 s = "alex SB alet haha" 3 ret = s.rpartition('e') 4 print(ret) 5 ('alex SB al', 'e', 't haha')
def split(self, sep=None, maxsplit=-1): #分割,从左向右匹配
实例:
1 ##分割 2 s = "alexalex" 3 #匹配字符串e进行分割,同时不再显示e 4 ret = s.split("e") 5 print(ret) 6 ['al', 'xal', 'x'] 7 #将匹配到第一次出现的e进行分割,同时不再显示e 8 ret1 = s.split("e",1) 9 print(ret1) 10 ['al', 'xalex']
def rsplit(self, sep=None, maxsplit=-1): #分割,从右向左匹配
实例:
1 s = "alexalex" 2 #从右向左匹配字符串e进行分割,同时不再显示e 3 ret = s.rsplit("e") 4 print(ret) 5 ['al', 'xal', 'x'] 6 #将匹配到第一次出现的e进行分割,同时不再显示e 7 ret1 = s.rsplit("e",1) 8 print(ret1) 9 ['alexal', 'x']
def splitlines(self, keepends=None): #按照行('\r', '\r\n', \n')分隔,返回一个包含各行作为元素的列表,如果参数 keepends 为 False,不包含换行符,如果为 True,则保留换行符。
实例:
1 str1 = 'ab c\n\nde fg\rkl\r\n' 2 print(str1.splitlines()) 3 ['ab c', '', 'de fg', 'kl'] 4 str2 = 'ab c\n\nde fg\rkl\r\n' 5 print(str2.splitlines(True)) 6 ['ab c\n', '\n', 'de fg\r', 'kl\r\n']
def startswith(self, prefix, start=None, end=None): #是否以XX开始
实例:
1 ##是否以XX开始的 2 temp = "hello" 3 print(temp.startswith('h')) 4 True 5 #字符串里大于0小于2的字符中,是否有以e结尾的 6 print(temp.startswith('e',0,2)) 7 False
def swapcase(self): #大小写转换,大写变小写,小写变大写
实例:
1 s = "aLeC" 2 print(s.swapcase()) 3 AlEc
def title(self): #变成标题,将开头字母变成大写
实例:
1 s = "the school" 2 ret = s.title() 3 print(ret) 4 The School
def translate(self, table): #
'''
转换,需要先做一个对应表,最后一个表示删除字符集合
intab = "aeiou"
outtab = "12345"
trantab = maketrans(intab, outtab)
str = "this is string example....wow!!!"
print str.translate(trantab, 'xm')
'''
def upper(self): #变成大写
实例:
1 a = "hello world" 2 print(a.upper()) 3 HELLO WORLD
def zfill(self, width): # 方法返回指定长度的字符串,原字符串右对齐,前面填充0,不常用,可忽略
四、列表
1、创建:
1 name_list = ["zhao","qian","sun","li"]
或者 2 name_list = list(["zhao","qian","sun","li",])
2、基本操作:
- 索引
- 切片
- 追加
- 删除
- 长度
- 循环
- 包含
索引
实例:
name_list = ["zhao","qian","sun","li"] print(name_list[1]) qian
切片
实例:
name_list = ["zhao","qian","sun","li"] print(name_list[0:2]) ['zhao', 'qian']
长度
实例:
name_list = ["zhao","qian","sun","li"] print(len(name_list)) 4 print(name_list[2:len(name_list)]) ['sun', 'li']
删除
实例:
name_list = ["zhao","qian","sun","li"] print(name_list) ['zhao', 'qian', 'sun', 'li'] del name_list[1] print(name_list) ['zhao', 'sun', 'li'] ##或者指定一个段 del name_list[1:3] print(name_list) ['zhao']
循环
实例:
name_list = ["zhao","qian","sun","li"] for i in name_list: print(i) zhao qian sun li
3、列表内部功能
def append(self, p_object): # 向后追加
实例:
name_list = ["zhao","qian","sun","li"] name_list.append('haha') print(name_list) ['zhao', 'qian', 'sun', 'li', 'haha']
def clear(self): #清除列表
实例:
name_list = ["zhao","qian","sun","li"] print(name_list) ['zhao', 'qian', 'sun', 'li'] name_list.clear() print(name_list) []
def copy(self): #复制列表
实例:
name_list = ["zhao","qian","sun","li"] print(name_list) ['zhao', 'qian', 'sun', 'li'] name_list2 = name_list.copy() print(name_list2) ['zhao', 'qian', 'sun', 'li']
def count(self, value): #统计元素出现的个数
实例:
name_list = ["zhao","qian","sun","li"] print(name_list.count('li')) 1
def extend(self, iterable): #扩展,将一组数据批量追加
实例:
name_list = ["zhao","qian","sun","li"] temp = [11,22,33,331] name_list.extend(temp) print(name_list) ['zhao', 'qian', 'sun', 'li', 11, 22, 33, 331]
def index(self, value, start=None, stop=None): #索引,获取指定元素的索引位置
实例:
name_list = ["zhao","qian","sun","li"] print(name_list.index("li")) 3
def insert(self, index, p_object): #插入,在索引指定位置,插入元素
实例:
name_list = ["zhao","qian","sun","li"] name_list.insert(1,"zhou") print(name_list) ['zhao', 'zhou', 'qian', 'sun', 'li']
def pop(self, index=None): #移除某个元素
实例:
name_list = ["zhao","qian","sun","li"] print(name_list) ['zhao', 'qian', 'sun', 'li'] name_list.pop() print(name_list) ['zhao', 'qian', 'sun']
##pop还可以在原列表中移除掉的最后一个值,并将其赋值给变量ret name_list = ["zhao","qian","sun","li"] ret = name_list.pop() print(ret) li
def remove(self, value): #移除,只能移除从左边往右找到的第一个参数
实例:
name_list = ["zhao","qian","qian","sun","li"] name_list.remove('qian') print(name_list) ['zhao', 'qian', 'sun', 'li']
def reverse(self): #翻转列表中的元素的顺序
实例:
name_list = ["zhao","qian","sun","li"] name_list.reverse() print(name_list) ['li', 'sun', 'qian', 'zhao']
def sort(self, key=None, reverse=False): #排序
实例:
name_list = ["zhao","qian","sun","li"] name_list.sort() print(name_list) ['li', 'qian', 'sun', 'zhao']
五、元组
特征:元组的元素不允许修改 ,不能进行增删改。
1、创建
name_tuple = ('alex','eric','alex','hhh')
或者
name_tuple = tuple(('alex','eric','alex','hhh'))
2、基本操作
- 索引
- 切片
- 循环
- 长度
- 包含
索引
实例:
name_tuple = ('alex','eric','alex','hhh') print(name_tuple[1]) eric
长度(len)
实例:
name_tuple = ('alex','eric','alex','hhh') print(len(name_tuple)) 4 print(name_tuple[len(name_tuple) - 1]) hhh
切片
实例:
name_tuple = ('alex','eric','alex','hhh') print(name_tuple[0:1]) ('alex',)
for循环
实例:
name_tuple = ('alex','eric','alex','hhh') for i in name_tuple: print(i) alex eric alex hhh
del 删除整个元组
实例:
del 不可以删除元组的元素,但是可以删除整个元组,删除后print会报错没有定义这个元组
name_tuple = ('alex','eric','alex','hhh') del name_tuple print(name_tuple) NameError: name 'name_tuple' is not defined
3、元组内部功能
def count(self, value): # 计算元素出现的个数
实例:
name_tuple = ('alex','eric','alex','hhh') print(name_tuple.count("alex")) 2
def index(self, value, start=None, stop=None): # 获取指定元素的索引位置
实例:
name_tuple = ('alex','eric','alex','hhh') print(name_tuple.index("hhh")) 3
六、字典
特征:无序的,不支持切片
1、创建字典:
user_info = {"name":"wang",'age':25} 或者 user_info = dict({"name":"wang",'age':25})
2、常用操作:
- 索引
- 新增
- 删除
- 键、值、键值对
- 循环
- 长度
索引
实例:
user_info = { "name":"alex", "age":22, "gender":"Man" } print(user_info["name"]) alex print(user_info["age"]) 22 print(user_info["gender"]) Man
删除
实例:
user_info = { "name":"alex", "age":22, "gender":"Man" } print(user_info) {'gender': 'Man', 'name': 'alex', 'age': 22} del user_info["age"] print(user_info) {'gender': 'Man', 'name': 'alex'}
循环
实例:
user_info = { "name":"alex", "age":22, "gender":"Man" } ##循环,默认输出key for i in user_info: print(i) age gender name
键、值、键值对
实例:
user_info = { "name":"alex", "age":22, "gender":"Man" } #获取所有的键 print(user_info.keys()) dict_keys(['age', 'gender', 'name']) #获取所有的值 print(user_info.values()) dict_values([22, 'Man', 'alex']) #获取所有的键值对 print(user_info.items()) dict_items([('age', 22), ('gender', 'Man'), ('name', 'alex')])
user_info = { "name":"alex", "age":22, "gender":"Man" } for i in user_info.keys(): print(i) name gender age
user_info = { "name":"alex", "age":22, "gender":"Man" } for i in user_info.values(): print(i) alex Man 22
user_info = { "name":"alex", "age":22, "gender":"Man" } for k,v in user_info.items(): print(k) print(v) name alex gender Man age 22
三、字典内置方法
def clear(self): #清除字典所有元素
实例:
user_info = { "name":"alex", "age":22, "gender":"Man" } user_info.clear() print(user_info) {}
def copy(self): # 拷贝字典
实例:
user_info = { "name":"alex", "age":22, "gender":"Man" } user_info1 = user_info.copy() print(user_info1) {'name': 'alex', 'age': 22, 'gender': 'Man'}####直接赋值和 copy 的区别
dict = { 'name':'alex','age':25,'sex':'man','bobby':[1,2,3]} dict1 = dict dict2 = dict.copy() ##修改数据 dict['name']='root' dict['bobby'].remove(3) #输出结果
#实例中 dict2 其实是 dict1 的引用(别名),所以输出结果都是一致的,dict3 父对象进行了深拷贝,不会随dict1 修改而修改,子对象是浅拷贝所以随 dict1 的修改而修改
print(dict) {'name': 'root', 'age': 25, 'bobby': [1, 2], 'sex': 'man'} print(dict1) {'name': 'root', 'age': 25, 'bobby': [1, 2], 'sex': 'man'} print(dict2) {'name': 'alex', 'age': 25, 'bobby': [1, 2], 'sex': 'man'}
def fromkeys(*args, **kwargs): #用于创建一个新字典,以序列seq中元素做字典的键,value为字典所有键对应的初始值。
实例:
seq = ('name', 'age', 'sex') dict = dict.fromkeys(seq) print(dict) {'name': None, 'sex': None, 'age': None}
seq = ('name', 'age', 'sex') dict = dict.fromkeys(seq, 10) print(dict) {'name': 10, 'sex': 10, 'age': 10}
def get(self, k, d=None): # 根据key获取值,如果key不存在,可以指定一个默认值
实例:
user_info = { "name":"alex", "age":22, "gender":"Man" } val = user_info.get("age") print(val) 22
user_info = {
"name":"alex",
"age":22,
"gender":"Man"
}
val = user_info.get("age111",'123')
print(val)
123
user_info = { "name":"alex", "age":22, "gender":"Man" } ##索引取值时,key不存在就会报错 print(user_info['age']) 22 print(user_info['age111']) KeyError: 'age111'
def items(self): # 以列表返回可遍历的(键, 值) 元组数组
实例:
user_info = { "name":"alex", "age":22, "gender":"Man" } print(user_info.items()) dict_items([('age', 22), ('gender', 'Man'), ('name', 'alex')]) ##for循环输出 for i,j in user_info.items(): print(i,":\t",j) age : 22 gender : Man name : alex
def keys(self): #以列表返回一个字典所有的键。
实例:
user_info = { "name":"alex", "age":22, "gender":"Man" } print(user_info.keys()) dict_keys(['age', 'gender', 'name'])
def has_key(self):#检查字典中指定key是否存在,适用于Python2.X,Python3没有此方法
key in dict :#key是否在字典中,是返回True
实例:
##python3.X 中没有has_key,可以使用in代替
user_info = { "name":"alex", "age":22, "gender":"Man" } ret= "age" in user_info.keys() print(ret) True ret= "ag" in user_info.keys() print(ret) False
def pop(self, k, d=None): #移除字典中指定的键值对
实例:
user_info = { "name":"alex", "age":22, "gender":"Man" } print(user_info) {'age': 22, 'name': 'alex', 'gender': 'Man'} user_info.pop("age") print(user_info) {'name': 'alex', 'gender': 'Man'}
def popitem(self): #随机删除一对键值,因为在字典中没有顺序,都是无序的,在工作时如果遇到需要逐一删除项的工作,用popitem()方法效率很高
实例:
user_info = { "name":"alex", "age":22, "gender":"Man" } print(user_info) {'gender': 'Man', 'age': 22, 'name': 'alex'} user_info.popitem() print(user_info) {'age': 22, 'name': 'alex'}
def setdefault(self, k, d=None): # 和get()方法类似, 如果键已经不存在于字典中,将会添加键并将值设为默认值。
实例:
user_info = { "name":"alex", "age":22, "gender":"Man" } print(user_info.setdefault("name",None)) alex print(user_info.setdefault("like",None)) None
def update(self, E=None, **F): #更新,将其他字典的键值对更新进去
实例:
user_info = { "name":"alex", "age":22, "gender":"Man" } test = { "ss" : "23", "a2" : "sf" } print(user_info) {'gender': 'Man', 'name': 'alex', 'age': 22} user_info.update(test) print(user_info) {'ss': '23', 'gender': 'Man', 'age': 22, 'a2': 'sf', 'name': 'alex'}
def values(self): #以列表返回字典中的所有值。
实例:
user_info = { "name":"alex", "age":22, "gender":"Man" } print(user_info.values()) dict_values(['Man', 22, 'alex'])
其他
1、enumrate
为可迭代的对象添加序号
#enumerate自动生成一列,默认从零开始 li = ["电脑","笔记本","键盘","CD"] for key,item in enumerate(li): print(key,item) 0 电脑 1 笔记本 2 键盘 3 CD
#enumerate自动生成一列,指定从1开始 li = ["电脑","笔记本","键盘","CD"] for key,item in enumerate(li,1): print(key,item) 1 电脑 2 笔记本 3 键盘 4 CD
li = ["电脑","笔记本","键盘","CD"] for key,item in enumerate(li,1): print(key,item) inp = input("请输入商品:") # 将字符转换int inp_num = int(inp) print(li[inp_num - 1]) 1 电脑 2 笔记本 3 键盘 4 CD 请输入商品:2 笔记本
2、range和xrange(2.7)
xrange,用来获取指定范围内的数,range(0,100000) 用到的时候才会创建到内存中,适用于Python2.7
for i in xrange(1,4): print(i) 1 2 3
#range,用来获取指定范围内的数,range(0,100000) 会在内存中一下全部创建出来,适用于Python3.X
print(range(1,4)) for i in range(1,4): print(i) 1 2 3
# #第三个数字2是间隔
for i in range(1,10,2): print(i) 1 3 5 7 9
##倒着输出
for i in range(10,1,-2): print(i) 10 8 6 4 2
li = ['alex','eirc'] li_len = len(li) for i in range(0,li_len): print(i,li[i]) 0 alex 1 eirc