Python - 基础数据类型
字符串(str)
大小写相关
upper()
有返回值,返回值为一个新的字符串
全部转大写
str1 = 'helLo World'
str2 = str1.upper()
print(str2) # HELLO WORLD
lower()
有返回值,返回值为一个新的字符串
全部转小写
str1 = 'helLo World'
str2 = str1.lower()
print(str2) # hello world
capitalize()
有返回值,返回值为一个新的字符串
首字母大写
str1 = 'helLo World'
str2 = str1.capitalize()
print(str2) # Hello world
title()
有返回值,返回值为一个新的字符串
每个单词首字母大写
str1 = 'helLo World'
str2 = str1.title()
print(str2) # Hello World
swapcase()
有返回值,返回值为一个新的字符串
大小写互换
str1 = 'helLo World'
str2 = str1.swapcase()
print(str2) # HELlO wORLD
判断类方法
isdigit()
有返回值,返回值为 bool 类型
是否全是数字
str1 = "123"
print(str1.isdigit()) # True
str2 = 'abc'
print(str2.isdigit()) # False
str3 = 'abc123'
print(str3.isdigit()) # False
isalpha()
有返回值,返回值为 bool 类型
是否全是字母
str1 = "123"
print(str1.isalpha()) # False
str2 = 'abc'
print(str2.isalpha()) # True
str3 = 'abc123'
print(str3.isalpha()) # False
isalnum()
有返回值,返回值为 bool 类型
是否全是字母或数字
str1 = "123"
print(str1.isalnum()) # True
str2 = 'abc'
print(str2.isalnum()) # True
str3 = 'abc123'
print(str3.isalnum()) # True
isspace()
有返回值,返回值为 bool 类型
是否全是空白字符
str1 = ' '
print(str1.isspace()) # True
str2 = 'qwert'
print(str2.isspace()) # False
str3 = ''
print(str3.isspace()) # False,空字符串不是空白字符串
islower()
有返回值,返回值为 bool 类型
是否全小写
str1 = 'hello world'
print(str1.islower()) # True
str2 = 'HELLO WORLD'
print(str2.islower()) # False
str3 = 'Hello World'
print(str3.islower()) # False
isupper()
有返回值,返回值为 bool 类型
是否全大写
str1 = 'hello world'
print(str1.isupper()) # False
str2 = 'HELLO WORLD'
print(str2.isupper()) # True
str3 = 'Hello World'
print(str3.isupper()) # False
startswith(x[,start,end])
startswith(x[,start,end])
有返回值,返回值为 bool 类型
是否以 x 开头,支持切片
str1 = 'hello world'
print(str1.startswith('h')) # True
print(str1.startswith('ell')) # False
print(str1.startswith('ell',1)) # True
print(str1.startswith('rld')) # False
print(str1.startswith('world')) # False
endswith(x[,start,end])
有返回值,返回值为 bool 类型
是否以 x 结尾,支持切片
str1 = 'hello world'
print(str1.endswith('h')) # False
print(str1.endswith('hell')) # False
print(str1.endswith('llo')) # False
print(str1.endswith('llo',0,5)) # True
print(str1.endswith('world')) # True
查找/统计
find 不报错,index 会报错
find(x[,start,end])
有返回值,返回值为元素 x 的索引,找不到则返回值为-1
查找,找到返回索引, 找不到返回-1,支持切片
str1 = 'Hello World'
print(str1.find('H',0,4)) # 0
print(str1.find('H',2,4)) # -1
print(str1.find('l')) # 2
print(str1.find('a')) # -1
index(x[,start,end])
有返回值,返回值为元素 x 的索引
查找,找到返回元素 x 的索引,找不到报错,支持切片
str1 = 'Hello World'
print(str1.index('Hel')) # 0
print(str1.index('el')) # 1
print(str1.index('l')) # 2
print(str1.index('l',1,5)) # 2
print(str1.index('w')) # ValueError: substring not found
count(x[,start,end])
有返回值,返回值为元素 x 出现的次数
统计元素 x 出现的次数,支持切片
str1 = 'Hello World'
print(str1.count('e')) # 1
print(str1.count('e',2,6)) # 0
print(str1.count('l')) # 3
print(str1.count('l',2,6)) # 2,最后一个'l'不在str1[2:6]中
替换/分割/拼接
replace(old,new[,n])
无返回值
替换,可以指定替换 n 次,不指定全部替换
str1 = "2026-01-09"
print(str1.replace("-","/")) # 2026/01/09
print(str1.replace("-","/",1)) # 2026/01-09
print(str1.replace("0","***")) # 2***26-***1-***9
split(x[,n])
有返回值,返回值为一个新的字符串
以 x 为分隔符,从左向右将字符串分割成列表,可以指定分割 n 次,不指定全分割
str1 = "2026-01-09"
str2 = str1.split("-",1)
print(str2, type(str2)) # ['2026', '01-09'] <class 'list'>
str3 = str1.split("0")
print(str3, type(str3)) # ['2', '26-', '1-', '9'] <class 'list'>
rsplit(x[,n])
有返回值,返回值为一个新的字符串
和 split 一样,从右向左分割
str1 = "2026-01-09"
str2 = str1.rsplit("-")
print(str2, type(str2)) # ['2026', '01', '09'] <class 'list'>
str3 = str1.rsplit("0",1)
print(str3, type(str3)) # ['2026-01-', '9'] <class 'list'>
join(iterable)
有返回值,返回值为一个新的字符串
使用指定的字符对可迭代的对象进行拼接
str1 = 'abc'
str2 = '-'.join(str1)
print(str2, type(str2)) # a-b-c <class 'str'>
str3 = '123'.join(str1)
print(str3, type(str3)) # a123b123c <class 'str'>
list1 = ['a', 'b', 'c']
str4 = '*'.join(list1)
print(str4, type(str4)) # a*b*c <class 'str'>
去除空白字符
有返回值,返回值为一个新的字符串
只能去两端,不能去中间
str1 = " python "
# strip() 去除左右空格
print(str1.strip()) # 'python'
# lstrip() 去除左边空格
print(str1.lstrip()) # 'python '
# rstrip() 去除右边空格
print(str1.rstrip()) # ' python'
对齐/填充
str1 = "python"
# center(num, 'str') 居中
print(str1.center(10,'*')) # **python**
# ljust(num, 'str') 左对齐
print(str1.ljust(10,'*')) # python****
# rjust(num, 'str') 右对齐
print(str1.rjust(10,'*')) # ****python
# zfill() 左边补0
print(str1.zfill(10)) # 0000python
切片
str[start🔚step],start 表示开始位置,end 表示结束位置,step 表示步长,可以为负数,从右向左取
顾头不顾尾:start 可以取到,但是 end 取不到
str1 = "python"
print(str1[0:2]) # py
print(str1[::-1]) # nohtyp
print(str1[::2]) # pto
列表(list)
增
append(x)
无返回值
末尾添加一个元素 x
list1 = [1, 2, 3]
list1.append(4)
print(list1) # [1, 2, 3, 4]
list1.append([4, 5])
print(list1) # [1, 2, 3, 4, [4, 5]],与extend([4,5])对比
extend(iterable)
无返回值
末尾追加多个元素,参数为可迭代的数据类型
list1 = [1, 2, 3]
list1.extend('python')
print(list1) # [1, 2, 3, 'p', 'y', 't', 'h', 'o', 'n']
list2 = [4, 5]
list1.extend(list2)
print(list1) # [1, 2, 3, 'p', 'y', 't', 'h', 'o', 'n', 4, 5],与append([4, 5])对比
insert(i, x)
无返回值
在指定位置(索引为 i)插入元素 x
list1 = [1, 2, 3]
list1.insert(1,4)
print(list1) # [1, 4, 2, 3]
删
remove(x)
无返回值
删除第一个元素 x
list1 = [1, 2, 3, 2]
list1.remove(2)
print(list1) # [1, 3, 2]
pop([x])
有返回值
删除并返回一个元素,参数为元素索引,可以根据索引指定元素进行删除
无参数时,删除并返回最后一个元素;有参数时,删除并返回指定索引对应的元素
list1 = [1, 2, 3, 2]
print(list1.pop()) # 2,被删除元素
print(list1) # [1, 2, 3]
print(list1.pop(0)) # 1,被删除元素
print(list1) # [2, 3]
clear()
无返回值
清空列表
list1 = [1, 2, 3, 2]
list1.clear()
print(list1) # []
del list[i]
无返回值
指定索引元素时,删除指定索引元素;不指定具体元素时,将整个列表从内存中删除
list1 = [1, 2, 3, 2]
del list1[1]
print(list1) # [1, 3, 2]
del list1
print(list1) # 报错,列表list1已从内存中删除,NameError: name 'list1' is not defined.
改(通过索引)
list1 = [1, 2, 3]
list1[0] = 100
print(list1) # [100, 2, 3]
查/统计
index(x)
有返回值,返回值为第一个元素 x 对应的索引;无元素 x 时会报错
list1 = [1, 2, 2, 3]
print(list1.index(2)) # 1
# print(list1.index(4)) # 报错,4不在列表list1中,ValueError: 4 is not in list
count(x)
有返回值,返回值为元素 x 出现的次数
统计元素 x 在列表中出现的次数
list1 = [1, 2, 2, 3, 3, 3, 3]
print(list1.count(1)) # 1
print(list1.count(2)) # 2
print(list1.count(3)) # 4
print(list1.count(4)) # 0
排序/反转
sort([reverse=True])
无返回值
对原列表进行操作,不会生成新列表
只对数字列表进行排序,reverse 默认为 False,升序排列,为 True 时,降序排列
list1 = [3, 1, 5, 2]
list1.sort()
print(list1) # [1, 2, 3, 5]
list2 = [3, 1, 5, 2]
list2.sort(reverse=True)
print(list2) # [5, 3, 2, 1]
sorted(list)
有返回值,返回值为一个已排序的新列表,会生成新列表
reverse 默认为 False,升序排列;为 True 时,降序排列
list1 = [3, 1, 5, 2]
list2 = sorted(list1)
print(list2) # [1, 2, 3, 5]
list3 = sorted(list1, reverse=True)
print(list3) # [5, 3, 2, 1]
reverse()
无返回值
反转列表,对原列表进行反转操作
list1 = [3, 1, 5, 2]
list1.reverse()
print(list1) # [2, 5, 1, 3]
拷贝
浅拷贝
有返回值,返回值为一个新的列表
特点:
- 新列表 ≠ 原列表(地址不同)
- 内部的子列表地址相同
原因:外层拷贝了,内层没拷贝
import copy
list1 = [1, 2, [3, 4]]
# 法一
list2 = list1.copy()
print(list2) # [1, 2, [3, 4]]
# 法二
list3 = list1[:]
print(list3) # [1, 2, [3, 4]]
# 法三
list4 = copy.copy(list1)
print(list4) # [1, 2, [3, 4]]
# 验证内部的字列表地址相同
list1[2].append(5)
print(list1) # [1, 2, [3, 4, 5]]
print(list2) # [1, 2, [3, 4, 5]]
print(list3) # [1, 2, [3, 4, 5]]
print(list4) # [1, 2, [3, 4, 5]]
深拷贝
有返回值,返回值为一个新的列表
特点:
外层是新的
内层也是新的
互不影响
import copy
list1 = [1, 2, [3, 4]]
# 深拷贝唯一方式
list2 = copy.deepcopy(list1)
print(list2) # [1, 2, [3, 4]]
# 验证深拷贝
list1[2].append(5)
list2[2].append(6)
print(list1) # [1, 2, [3, 4, 5]]
print(list2) # [1, 2, [3, 4, 6]]
切片
list1 = [0, 1, 2, 3, 4]
print(list1[1:4]) # [1, 2, 3]
print(list1[::-1]) # [4, 3, 2, 1, 0]
print(list1[::2]) # [0, 2, 4]
成员判断
有返回值,返回值为 bool 类型
x in list:判断元素 x 是否在列表 list 中
x not in list:判断元素 x 是否不在列表 list 中
list1 = ['a', 'b', 'c']
print('a' in list1) # True
print('b' in list1) # True
print('c' in list1) # True
print('d' in list1) # False
字典(dictionary)
dict = key → value 的映射,key 必须不可变
增
dict1 = {'k1': 'v1', 'k2': 'v2'}
# 直接赋值新增,不安全(字典中已有指定键时,会修改对应的key)
dict1['k3'] = 'v3'
print(dict1) # {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'}
dict1['k1'] = 'v1_new'
print(dict1) # {'k1': 'v1_new', 'k2': 'v2', 'k3': 'v3'}
# setdefault(key,value)
# 无返回值
# 若key不存在,则新增;若key已存在,不做操作
dict1.setdefault('k4', 'v4')
print(dict1) # {'k1': 'v1_new', 'k2': 'v2', 'k3': 'v3', 'k4': 'v4'}
dict1.setdefault('k2', 'v2_new')
print(dict1) # {'k1': 'v1_new', 'k2': 'v2', 'k3': 'v3', 'k4': 'v4'}
删
pop(key)
有返回值,若 key 存在,返回删除的 key 对应的 value;若 key 不存在,可指定返回值
若 key 存在,则删除 key 以及对应的 value;若 key 不存在,可指定返回值,不指定会报错
dict1 = {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'}
print(dict1.pop('k1')) # v1
print(dict1) # {'k2': 'v2', 'k3': 'v3'}
# print(dict1.pop('k4')) # KeyError: 'k4'
print(dict1.pop('k5', '没有这个键')) # 没有这个键
print(dict1) # {'k2': 'v2', 'k3': 'v3'}
popitem()
Python 3.7+:删除最后一个
有返回值,返回值为删除的最后一个键值对
dict1 = {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'}
print(dict1.popitem()) # ('k3', 'v3')
print(dict1) # {'k1': 'v1', 'k2': 'v2'}
print(dict1.popitem()) # ('k2', 'v2')
print(dict1) # {'k1': 'v1'}
clear()
无返回值
清空字典
dict1 = {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'}
dict1.clear()
print(dict1) # {}
改
存在就覆盖,不存在就新增
dict1 = {'k1': 'v1', 'k2': 'v2'}
# 法一:直接修改
dict1['k1'] = 'v1_new'
print(dict1) # {'k1': 'v1_new', 'k2': 'v2'}
dict1['k3'] = 'v3'
print(dict1) # {'k1': 'v1_new', 'k2': 'v2', 'k3': 'v3'}
# 法二:update()
# 无返回值
# 存在就覆盖,不存在就新增
dict1.update({'k2': 'v2_new', 'k4': 'v4'})
print(dict1) # {'k1': 'v1_new', 'k2': 'v2_new', 'k3': 'v3', 'k4': 'v4'}
查
dict1 = {'k1': 'v1', 'k2': 'v2'}
# 法一:直接打印,不安全(字典中没有指定key时,会报错)
print(dict1['k1']) # v1
# print(dict1['k3']) # 报错,字典dict1中没有这个键,KeyError: 'k3'
# 法二:get(key)
# 有返回值,返回值为key对应的value
print(dict1.get('k2')) # v2
print(dict1.get('k3')) # 虽然字典dict1中没有这个键,但不会报错,返回'None'
print(dict1.get('k4', '没有这个键')) # 当没有这个键时,可自定义返回值
遍历
keys()
遍历 key
dict1 = {'k1': 'v1', 'k2': 'v2'}
for i in dict1:
print(i, end=' ') # k1 k2
for i in dict1.keys():
print(i, end=' ') # k1 k2
# 两个都是遍历key
values()
遍历 value
dict1 = {'k1': 'v1', 'k2': 'v2'}
for i in dict1.values():
print(i, end=' ') # v1 v2
items()
遍历键值对,可以解包赋值
dict1 = {'k1': 'v1', 'k2': 'v2'}
for i in dict1.items():
print(i, end=' ') # ('k1', 'v1') ('k2', 'v2')
print()
for k, v in dict1.items():
print(k, v, end=' ') # k1 v1 k2 v2
复制
和列表一样,有浅拷贝(copy())和深拷贝(deepcopy())
浅拷贝
copy()
import copy
dict1 = {'k1': 'v1', 'k2': [1, 2, 3]}
# dict1.copy()
dict2 = dict1.copy()
# copy.copy(dict1)
dict3 = copy.copy(dict1)
print(dict2) # {'k1': 'v1', 'k2': [1, 2, 3]}
print(dict3) # {'k1': 'v1', 'k2': [1, 2, 3]}
dict1['k2'].append(4)
print(dict1) # {'k1': 'v1', 'k2': [1, 2, 3, 4]}
print(dict2) # {'k1': 'v1', 'k2': [1, 2, 3, 4]}
print(dict3) # {'k1': 'v1', 'k2': [1, 2, 3, 4]}
深拷贝
deepcopy()
import copy
dict1 = {'k1': 'v1', 'k2': [1, 2, 3]}
dict2 = copy.deepcopy(dict1)
print(dict2) # {'k1': 'v1', 'k2': [1, 2, 3]}
dict1['k2'].append(4)
print(dict1) # {'k1': 'v1', 'k2': [1, 2, 3, 4]}
print(dict2) # {'k1': 'v1', 'k2': [1, 2, 3]}
fromkeys()
对字典中的 key 赋予同一个值,当这个值为可变对象时,改一个全部 key 对应的 value 都会发生变化
dict1 = dict.fromkeys(['a', 'b', 'c'], 0)
print(dict1) # {'a': 0, 'b': 0, 'c': 0}
# 值是同一个列表
dict2 = dict.fromkeys(['a', 'b', 'c'], [])
print(dict2) # {'a': [], 'b': [], 'c': []}
dict2['a'].append(1)
print(dict2) # {'a': [1], 'b': [1], 'c': [1]}
集合(set)
集合:可变的数据类型,它里面的元素必须是不可变的数据类型,无序,不重复。
{}
定义
# 法一 set()方法
set1 = set({1, 2, 3})
print(set1) # {1, 2, 3}
# 法二 直接定义
set2 = {1, 2, 3}
print(set2) # {1, 2, 3}
# set3 = {1, 2, 3, [2, 3], {'name': 'alex'}} # 报错,一个元素为列表(可变的)
# print(set3) # TypeError: unhashable type: 'list'
增
add(x)
增加元素 x
set1 = {'alex', 'wusir', 'ritian', 'egon', 'barry', 'barry'}
print(set1) # 输出结果无序,且无重复元素
set1.add('女神')
print(set1) # 新增'女神'一个元素
update(iterable)
和list的extend()方法差不多,迭代添加
set1 = {'alex', 'wusir', 'ritian', 'egon', 'barry', 'barry'}
print(set1) # 输出结果无序,且无重复元素
set1.update('abc')
print(set1) # 新增'a', 'b', 'c'三个元素
删
pop()
随机删除,有返回值,返回值为删除的元素
set1 = {'alex', 'wusir', 'ritian', 'egon', 'barry'}
set1.pop()
print(set1.pop()) # 有返回值
print(set1) # 随机删除
remove(x)
remove(x)
按照元素删除,有则删除,无则报错
set1 = {'alex', 'wusir', 'ritian', 'egon', 'barry'}
set1.remove('alex')
print(set1) # 'alex'元素被删除
# set1.remove('alex1') # 报错,没有'alex'这个元素
# print(set1) # KeyError: 'alex1'
clear()
清空集合
set1 = {'alex', 'wusir', 'ritian', 'egon', 'barry'}
print(set1)
set1.clear()
print(set1) # 输出结果为set(),表示空集合
del
set1 = {'alex', 'wusir', 'ritian', 'egon', 'barry'}
print(set1)
del set1
print(set1) # 报错,set1已从内存中删除,NameError: name 'set1' is not defined.
查
set1 = {'alex', 'wusir', 'ritian', 'egon', 'barry'}
for i in set1:
print(i)
# 输出结果无序
交集
两个集合共同的元素的集合
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
# 法一
print(set1 & set2) # 结果仍为集合,{4, 5}
# 法二
print(set1.intersection(set2)) # 结果仍为集合,{4,5}
反交集
两个集合除去交集外的元素的集合
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
# 法一
print(set1 ^ set2) # {1, 2, 3, 6, 7, 8}
# 法二
print(set1.symmetric_difference(set2)) # {1, 2, 3, 6, 7, 8}
## 并集
> 两个集合所有元素的集合
```python
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
# 法一
print(set1 | set2) # {1, 2, 3, 4, 5, 6, 7, 8}
# 法二
print(set1.union(set2)) # {1, 2, 3, 4, 5, 6, 7, 8}
差集
两个集合中,除去交集中的元素,各自独有的元素
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
# 法一
print(set1 - set2) # {1, 2, 3}
print(set2 - set1) # {8, 6, 7}
# 法二
print(set1.difference(set2)) # {1, 2, 3}
print(set2.difference(set1)) # {8, 6, 7}
子集与超集
set1 = {1, 2, 3}
set2 = {1, 2, 3, 4, 5, 6}
# set1 是否是 set2 的子集
print(set1 < set2) # True
print(set1.issubset(set2)) # True
# set2 是否是 set1 的子集
print(set2 < set1) # False
print(set2.issubset(set1)) # False
# set2 是否是 set1 的超集
print(set2 > set1) # True
print(set2.issuperset(set1)) # True
# set1 是否是 set2 的超集
print(set1 > set2) # False
print(set1.issuperset(set2)) # False
去重
li = [1, 2, 33, 33, 2, 1, 4, 5, 6, 6]
set1 = set(li)
print(set1, type(set1)) # {1, 2, 33, 4, 5, 6} <class 'set'>
li = list(set1)
print(li, type(li)) # [1, 2, 33, 4, 5, 6] <class 'list'>
不可变集合(frozenset)
frozenset 不可变集合,让集合变成不可变类型
s1 = {1, 2, 3}
print(s1, type(s1)) # {1, 2, 3} <class 'set'>
s2 = frozenset('barry')
print(s2, type(s2)) # frozenset({'r', 'y', 'a', 'b'}) <class 'frozenset'>
# frozenset可循环打印,也是无序的
for i in s2:
print(i, end=' ') # y a r b
浙公网安备 33010602011771号