Python 基础数据类型及常用操作
基础数据类型 Basic Data Type
-
不可变数据类型
-
Number(数字)
- int 整型
- float 浮点型
- bool 布尔值
- True
- False
- complex 复数
-
String(字符串)
-
# 字符串有四种形式 # 如下定义四个str 字符串变量 str1、str2、str3、str4 str1 = '我是单引号字符串' str2 = "我是双引号字符串" str3 = '''我是三单引号字符串''' str4 = """我是三双引号字符串""" # 字符串可以相加,可以与数字相乘,字符串之间不能相乘 print(str1 + str2) # 结果:我是单引号字符串我是双引号字符串 print(str3 * 2) # 结果:我是三单引号字符串我是三单引号字符串 # 字符串截取:索引、切片 # 1.索引 str_01 = 'hello,world!' print(str_01[0]) # 打印 'h' print(str_01[4]) # 打印 'o' # 2.切片 str[start:end:step] [开始:结束:步长] 左闭右开 str_01 = 'hello,world!' print(str_01[1:3:1]) # 打印 'el' print(str_01[-4:-1:1]) # 打印 'rld' # 字符串拼接:+ 相加、* 相乘 str_02 = 'abc' str_03 = 'def' print(str_02 + str3) # 'abcdef' print(str_02 * 2) # 'abcabc' # 字符串转义:需要在字符中使用特殊字符时,python 用反斜杠 \ 转义字符 ''' \(在行尾时) 续行符 \' 单引号 \" 双引号 \n 换行 \r 回车 \t 横向制表符 \v 纵向制表符 ''' a = 'I\'m python' # 此处 \' 真正打印显示的只有' # 字符串方法: # strip 默认去除字符串两边的所有空白符(空格、tab、换行),否则去除两边指定字符 str1 = ''' ab c ''' str2 = str1.strip() print(str1) # ab c print(str2) #ab c # lstrip = left strip # 默认去除字符串左边的所有空白符(空格、tab、换行),否则去除左边指定字符 str3 = ' abc ' str4 = str3.lstrip() print(str3) print(str4) # rstrip = right strip # 默认去除字符串右边的所有空白符(空格、tab、换行),否则去除右边指定字符 str5 = ' abc ' str6 = str5.rstrip() print(str5) print(str6) # upper # 字符串全部转成大写 str7 = 'hellO, pyThon!' str8 = str7.upper() print(str7) print(str8) # isupper # 判断字符串是否全部为大写 print(str8.isupper()) # lower # 字符串全部小写 str9 = 'HEllO, PyTHON!' str10 = str9.lower() print(str9) print(str10) # islower # 判断字符串是否全部为小写 print(str8.islower()) # count # 统计字符在字符串中出现次数 str11 = 'abcdhsbcjbcbeinejbrbibiecjnjbbrh' print(str11.count('a')) print(str11.count('a', 1, 10)) # 在指定位置统计 # index # 获取指定字符在字符串中的位置,找不到则报错 str12 = 'abcdhsbcjbcbeinejbrbibiecjnjbbrh' print(str12.index('bcjb')) print(str12.index('bcjb', 10, 11)) # split 根据指定内容分割字符串,返回值是一个列表 str13 = 'https://ssxxlive.top/' # url # split_list = str13.split('/') split_list = str13.split('x') print(split_list[2]) # startswith 判断字符串是否以指定内容开头 str14 = 'https://ssxxlive.top/' print(str14.startswith('https')) print(str14.startswith('httpss')) # endswith 判断字符串是否以指定内容结尾 str15 = 'https://ssxxlive.top/' print(str15.endswith('top/')) # find 查找指定字符在字符串中的位置,找不到则返回-1 str16 = 'https://ssxxlive.top/' print(str16.find('/')) print(str16.find('sss')) # rfind 从字符串结尾查找指定字符在字符串中的位置,找不到则返回-1 str18 = 'https://ssxxlive.top/' print(str18.rfind('/')) # replace 替换字符串,三个参数:被替换的字符、想替换成什么、替换の次数 str19 = 'https://ssxxlive.toptoptoptop/' print(str19.replace('top', 'com')) print(str19.replace('top', 'com', 2)) # capitalize 首字母转换成大写 str19 = 'hello, i\'m zero!' str20 = str19.capitalize() print(str19) print(str20) # Hello, i\'m zero! # isdecimal 判断字符串是否全部由十进制组成 str24 = 'abc123' str25 = '01231' print(str24.isdecimal()) print(str25.isdecimal()) # isdigit 判断字符串是否全部由数字组成 str26 = 'abc123' str27 = '11011' print(str26.isdigit()) print(str27.isdigit()) # encode 字符串根据指定编码格式转换为字节 str28 = '中国' b = str28.encode('UTF-8', errors='encode_error') # 编码 print(b) # bytes.decode 字节根据指定编码格式转换为字符串 str29 = bytes.decode(b, 'UTF-8', errors='decode_error') # 解码 print(str29) # join 以给定的字符串为分隔符,将序列中所有元素拼接为一个新的字符串 str30 = 'abc' print(str30.join(['test1', 'test2', 'test3'])) # test1abctest2abctest3 # 反转字符串 str1 = 'hello,world!' list1 = list(str1) list1.reverse() str2 = ''.join(list1) print(str2) # 字符串反转输出 print(str2[-1::-1]) # 字符串格式化 % ''' 常见占位符: %s 格式化字符串 %d 格式化整数 %u 格式化无符号整型 %f 格式化浮点数字,可指定小数点后的精度 ''' name = 'zero' hobby = 'python' a = 'Hello,i am %s,i like %s'%(name, hobby) print(a) # Hello,i am zero,i like python # format # 第一种:根据{}以及参数格式化,顺序和个数必须对上 name = 'zero' hobby = 'python' a = 'Hello,i am {},i like {}'.format(name, hobby) print(a) # Hello,i am zero,i like python # 第二种:{}中填索引,根据索引获取参数 p = 'python' w = 'me' a = '{0} is good,many people like {0},{1} too'.format(p, w) print(a) # python is good,many people like python,me too # 第三种,根据关键字 e = '我叫{name},今年{age}岁,练习唱跳{year}年, 我叫{name}'.format(name='zs', age=3 + 96, year='2.5') print(e) # 我叫zs,今年99岁,练习唱跳2.5年, 我叫zs # *** f-string:python3.6之后的格式化字符串方法,推荐使用 name = 'zs' age = 3 + 96 year = '2.5' a = f'我叫{name},今年{age}岁,练习唱跳{year}年, 我叫{name}' print(a) # 我叫zs,今年99岁,练习唱跳2.5年, 我叫zs # 补充 # max() 求字符串中最大的字母 print(max('abcABC')) # c # min() 求字符串中最小的字母 print(min('abcABC')) # A
-
-
Tuple(元组)
-
# 新建一个空元组 tuple_01 = tuple() print(tuple_01) # 新建一个元组 tuple_02 = (1, 2, 3, 4, True) print(tuple_02) # 创建一个只有一个元素的元组时,那个元素后面要加上逗号 tuple_03 = (1,) print(tuple_03) print(type(tuple_03)) print(tuple_02[0]) # 索引 print(tuple_02[1:3:]) # 切片 print(tuple_02[-1::-1]) # 元组倒序输出 # index 返回某个元素在元组中的索引(下标) print(tuple_02.index(4)) # 3 # count 统计 print(tuple_02.count(1)) # 2 # len 计算元组中元素的个数 print("元组的长度是:%s"%(len(tuple_02))) # 5 # max 返回元组中最大值 print(max(tuple_02)) # 4 # min 返回元组中最小值 print(min(tuple_02)) # 1 # 删除整个元组 del tuple_02 # 元组中如果有可迭代对象,可迭代对象是可以修改的 tuple_04 = (1, 2, 3, ['abc', 'qwer']) print(tuple_04) tuple_04[3][0] = 1 print(tuple_04)
-
-
-
可变数据类型
-
List(列表)
-
list1 = [] # 创建一个空列表 list2 = list() # 创建一个空列表 list3 = [1, 2, 3, 1, 'a', 'a','abc', True, False] # in、not in print('abc' in list3) # 判断一个元素是否在列表中 print('abc' not in list3) # 判断一个元素是否不在列表中 # 列表查询内容: #索引、切片 print(list3[4]) print(list3[3:5]) # index 根据元素获取其在列表中索引,没有则报错 print(list3.index('abc')) # count 统计某个元素在列表中出现的次数 print(list3.count('zhangn')) # 列表添加内容: # append 追加到列表最后一位 list4 = [1, 2, 3, 'a'] list4.append('test_append') print(list4) # insert 将元素插入到列表指定位置,两个参数:1.插入位置的索引 2.要插入的元素 list4.insert(3, 'test_insert') print(list4) # extend 将另一个列表(序列)合并到当前列表 list5 = ['list51', 'list52'] list4.extend(list5) list4.extend('123') # 列表相加 将两个列表相加 print(list5 + list5) # ['list51', 'list52', 'list51', 'list52'] # 列表相乘 print(list5 * 2) # ['list51', 'list52', 'list51', 'list52'] # 删 # pop 默认删除最后一位,并且返回被删除的元素, # 如果加上索引值,则删除对应索引的内容 test_pop = ['test1', 'test2', 'test3'] print(test_pop.pop()) # 打印 test3 print(test_pop) # 打印 ['test1', 'test2'] print(test_pop.pop(0)) # 根据索引删除第0个 print(test_pop) # 打印 ['test2'] # remove 根据值删除元素 test_remove = ['test1', 'test2', 'test3'] test_remove.remove('test2') print(test_remove) # ['test1', 'test3'] # del 根据索引或者切片删除 test_del = ['test1', 'test2', 'test3'] del test_del[1] print(test_del) # ['test1', 'test3'] test_del1 = ['test1', 'test2', 'test3'] del test_del1[::2] print(test_del1) # clear 清空列表 test_clear = ['test1', 'test2', 'test3'] print(test_clear) test_clear.clear() print(test_clear) # 改 # 之间根据索引或切片修改,使用切片修改多个时,元素个数要对应上 test_update = ['test1', 'test2', 'test3'] test_update[0] = 'test4' print(test_update) test_update[::2] = 'test5', 'test6' print(test_update) # ['test5', 'test2', 'test6'] # 其它操作 list3 = [1, 2, 3, 1, 'a', 'a','abc', False, False] # 列表反转输出 print(list3[-1::-1]) # 列表反转 list3 = list3[-1::-1] print(list3) # reverse 反转 list3.reverse() print(list3) # sort 排序 list_01 = ['a', 'ac', 'abcd', 'abc', 'e', ['inner1', 'inner2']] # key 排序的根据 reverse 绝对排序的方向:正序或者倒序 # list_01.sort(key=len, reverse=True) print(list_01) # copy 复制 浅复制 list_02 = list_01.copy() print(list_01) list_01[5][0] = 'zhangnan' print(list_01) print(list_02) # 深复制 deepcopy import copy list_03 = copy.deepcopy(list_01) print(list_03) list_01[5][0] = 'zhangnan' print(list_01) print(list_03) list_04 = ['a', 'ac', 'abcd', 'abc', 'e', ['inner1', 'inner2']] print(len(list_04)) # 6 list_05 = [1, 3, 5, 2, 1] # max() 求列表中最大值 print(max(list_05)) # 5 # min() 求列表中最小值 print(min(list_05)) # 1
-
-
Set(集合)
-
Dictionary(字典)
-
# 新建字典 # 字典的键必须是不可变数据类型 str、number、(tuple不规范) dict1 = { 'name' : 'zhangnan', 'age' : 3, 'sex' : 'MM', 'hobby' : 'rap' } # 新建字典 dict2 = dict(name='zhangnan', age=3, sex='MM', hobby='rap') # 新建字典 dict3 = dict([(1, 2),(3, 4),(5, 6)]) # 新建字典 dict3 = dict(((1, 2),(3, 4),(5, 6))) print(dict1) print(dict2) # 查 print(dict1['hobbyy']) # 直接根据键查询,没有则报错 print(dict1.get('hobbyy', '查无此键')) # 使用get查询如果键不存在不会报错,并可自定义提示 # 增 dict1['income'] = 13000 # 直接设置键和值,如果值已经存在则修改 dict1['income'] = 14000 print(dict1) print(dict1.setdefault('intime', '20200601')) # 设置键和默认值,如果键已经存在则值不变 print(dict1) print(dict1.setdefault('intime', '20200605')) print(dict1) # 删 del dict1['income'] # del 根据键删除 print(dict1) print(dict1.pop('intime')) # pop 根据键删除 print(dict1) # popitem 在python3.5之前,随机删除,python3.6之后,删除最后一位 print(dict1.popitem()) print(dict1) dict1.clear() # 清空字典 print(dict1) # 改 dict1['income'] = 15000 # 根据键来修改值,没有则新增 print(dict1) dict1.update(income=18000, intime=20200606) # 可以更新单个或多个值 dict2 = {'balance' : 20000000} dict1.update(dict2) # 也可以合并另外一整个字典进来 print(dict1) print(len(dict1)) print(type(dict1)) print(type(str(dict1))) # # 遍历 for i in dict1.keys(): # keys()字典所有的键 print(i) for i in dict1.values(): # values()字典所有的值 print(i) for k, v in dict1.items(): # items()字典所有的键和值(元组) print(k, v) # 拆包 a, b, c = ('test1', 'test2', 'test3') print(a) # test1 print(b) # test2 print(c) # test3 a, *b = ('test1', 'test2', 'test3') a = 'test1' b = ('test2', 'test3') *a, b = ('test1', 'test2', 'test3') a = ('test1', 'test2') b = 'test3' # 字典嵌套 dict_test = { "code" : 200, 'date' : { 'info' : { 'username' : 'tester', 'token' : 'cbsbcbcbkjanxhuwe', }, 'favorite' : ['EURUSD', 'USOil', 'CHA50'], 'balance' : 5000 }, 'message' : 'success', 'status' : 'True' }
-
-