day08-python
day08-python
字符串
字符串的创建
使用 ' 或 ""来创建字符串
例:str1="hello world" 或 str2='hello world'
访问字符串中的值
变量[下标]
变量[头下标:尾下标]
索引值从0为开始,-1从末尾开始
注:python不支持单字符类型,单字符在python中也是作为一个字符串使用。
- 代码
# 访问字符串中的值
str1="123456789"
print(str1[3]) # 输出第3位的字符串
print(str1[-1]) # 输出最1位字符串
print(str1[1:7])# 输出第1到第6位的字符串,区间是左闭右开
print(str1[:3]) # 从第1位到第3位
print(str1[:]) # 输出所有
print(str1[4:]) # 第4位到最后一位
结果:

字符串的拼接
使用 + 或者 "str1" "str2"
- 代码
# 字符串的拼接
str1="hello" "world"+"haha"
print(type(str1))
print(str1)
结果:

转义字符
使用 \ 反斜杠
需要使用特殊字符时,使用 \
例:
\\ 输出\
\' 输出'
\n 换行
...
字符串运算符
+ 字符串连接
* 重复输出字符串
[] 通过索引获取指定字符串
[:] 截取字符串的一部分
in 成员运算符-字符串是否包含指定的字符串
not in 成员运算符-字符串不包含指定字符串
r 原始输出字符串
% 格式化字符串
- 代码
# 字符串运算符
str1="hrllo"
str2="world"
print(str1+str2)
print(str1*2+"\t"+str2*3)
print("a" in str1)
print("w" in str2)
print(r"hello\t world\nhaha")
print("%s %s" %(str1,str2))
结果:

字符串格式化
格式:
print("%s %d %s" %(str1,123,str2))
三引号
格式:
"""
内容
"""
三引号允许一个字符跨行,字符串可以包含换行符、制表符等
f-string
f-string:字面量格式化字符串
作用:它会将变量或表达式计算后的值替换进去
格式:
f"str1{变量名}"
- 代码
# f-sting 字面量格式化字符串
name="yaya"
print(f"hello {name}")
结果:

字符串内建函数
查找
count(str,beg,end) 查找指定字符串在指定范围内出现的次数
find(str,beg,end) 查找指定字符串的下标,没有查询到返回-1
rfind(str,beg,end) 从右边开始查找
index(str,beg,end) 查找指定字符串的下标,没有查询到返回异常
rindex(str,beg,end) 从右边开始查找
len(str) 字符串的长度
max(str) 返回字符串中的最大字母
min(str) 返回字符串中的最小字母
转换
capitalize() 将字符串的第一个字符转换为大写
center(width,fillchar) 返回一个指定宽度的字符串,宽度小于原字符串的长度则原样返回,否则多余的部分使用fillchar填充,默认为空格
decode(encoding,errors) 解码
encode(encoding,errors) 编码
join(seq) 以指定字符串对seq进行分割,得到一个新的字符串
lower() 大写转小写
upper() 小写转大写
swapcase() 大写转小写,小写转大写
lstrip() 删除左边的空格
rstrip() 删除右边的空格
strip() 删除两边的空格
replace(old,new,max) 把字符串的old字符串替换成new字符串,max指定替换的次数
split(str,num) 以str为分隔符,截取字符串,num指定截取的个数,可以截取num+1个子字符串
title() 标题化
zfill(width) 返回长度为width的字符串,源字符串右对齐,前面填充0
判断
endswith(suffix,beg,end) 判断字符串是否以suffix结尾
startwith(substr,beg,end) 判断字符串是否以substr开始
isalnum() 判断字符串是否只包含字母和数字和汉字
isalpha() 判断字符串是否只包含字母和汉字
isdigit() 判断字符串是否只包含数字
islower() 判断字符串是否都是小写
isupper() 判断是否全是大写
isnumeric() 判断字符串是否全是数字
isspace() 判断字符串是否全是空白
istitle() 判断是否标题化
isdecimal() 判断字符串是否只包含10进制字符
列表
创建列表
list1=["str1","str2","str3"]
访问列表中的值
与字符串的索引一样,列表 索引从0开始
列表名[索引]
- 代码
# 列表
list01=["yaya","陈平安","宁姚","裴钱","崔东山","巉瀺"]
print(list01[3])
print(list01[:])
print(list01[2:])
print(list01[3:5])
print(list01[-1])
print(list01[-1::-1])
结果:

更新列表
列表名.append(str) :把元素放到列表的末尾
list[index]=str :修改指定位置的数据值
del list[index] : 删除指定位置的元素
列表脚本操作符
len(list) 列表的长度
list01+list02 组合
list *2 重复
str in list 元素是否存在与列表中
for x in list; 遍历
print(x,end="")
- 代码
# 列表脚本操作符
print(len(list01))
list02=["景清","暖树"]
list03=list01+list02
print(list03)
print(list03*2)
print("陈平安" in list01)
for x in list01:
print(x,end=" ")
print()
结果:

列表函数
len(list) 列表元素个数
max(list) 返回列表元素最大值
min(list) 返回列表元素最小值
lsit(seq) 将元组转换为列表
- 代码
# 列表函数
print(max(list01))
print(min(list01))
tupl01=("反派","贾生","仰止")
list04=list(tupl01)
print(type(tupl01))
print(type(list04))
结果:

列表方法
list.append(obj) 在列表末尾添加新的对象
list.count(obj) 统计某个元素在列表中出现的次数
list.extend(seq) 在列表末尾添加序列
list.index(obj) 查找指定对象第一次出现的索引
list.insert(index,obj) 指定位置插入对象
list.pop([index=-1]) 移除指定位置的对象,默认是最后一个
list.reverse() 列表反转
list.sort(key=None,reverse=False) 对原列表进行排序
list.clear() 清空列表
list.copy() 复制列表
- 代码
# 列表的方法
list05=["123","123","333","345","3454"]
print(list05.count("123"))
list05.extend(["aaa","bbbb"])
print(list05)
print(list05.index("aaa"))
list05.insert(0,"kkkkk")
print(list05)
list05.reverse()
print(list05)
list05.sort()
print(list05)
list05.clear()
print(list05)
结果:

元组
tuple与列表类似,元组的元素不能修改
元组的不可变指的是元组所指向的内存中的内容不可变,但元组的引用可以指向其他的对象
创建元组
tup=("google","baidu","firefox")
tup=() 创建空元组
注意:
元组中只包含一个元素时,元素后面需要添加逗号,否则括号会被当作运算符使用
- 代码
tuple02=("hello")
tuple03=("world",)
print(type(tuple02))
print(type(tuple03))
结果:

访问元组
通过下标索引来访问元组的值
tuple[索引]
- 代码
# 访问元组
tuple01=("陈平安","宁姚","裴钱","崔东山")
print(tuple01[0])
print(tuple01[0:])
print(tuple01[1:3])
print(tuple01[-1::-1])
print(tuple01[:2])
结果:

修改元组
元组中的元素值是不允许修改的,可以对元组进行连接组合
tuple01 + tuple02 连接两个元组
删除元组
元组中的元素不允许删除,可以删除整个元组
del tuple
元组运算符
len(tuple) 元素个数
tuple01 + tuple02 连接
tuple*2 复制
obj in tup 元素是否存在
for x in tup: 遍历
print(x)
- 代码
# 元组运算符
tuple01=("123","hello","world")
print(len(tuple01))
print(tuple01*2)
print("123" in tuple01)
print("zzz" in tuple01)
for x in tuple01:
print(x,end=" ")
print()
结果:

元组内置函数
len(tuple) 计算元组元素的个数
max(tuple) 返回元组中的最大值
min(tuple) 返回元组中的最小值
tuple(iterable) 将可迭代系列转换为元组
注意:
求最大和最小值时,元组中的数据类型必须一样,否则会报错
字典
字典是一种可变容器模型,可以存储任意类型对象。
字典是以键值对的方式保存数据
特点
- 键必须是唯一的,值不必是唯一的
- 键必须是不可变的数据类型,值可以是任意的数据类型
创建字典
dic={key1:value1,key2:value2,...}
dic={} 创建空字典
访问字典里面的值
通过键去获取值:
value=dic[key]
如果键不存在,报:KeyError: 错误
修改字典
dict["已存在key"]=value 修改
dict["不存在key"]=value 添加
- 代码
dict01={"name":"陈平安","age":"30","sex":"男"}
print(dict01)
dict01["age"]="18" # 修改
dict01["job"]="剑客" # 添加
print(dict01)
结果:

删除字典元素
删除其中一个元素
del dict[key]
清空字典
dict.clear()
删除字典
del dict
- 代码
dict01={"name":"陈平安","age":"30","sex":"男"}
print(dict01)
del dict01["age"]
print(dict01)
dict01.clear()
print(dict01)
del dict01
# print(dict01) # NameError: name 'dict01' is not defined. Did you mean: 'dict'?
结果:

字典内置函数
len(dict) 字典的长度
str(dict) 输出字典,可以打印的字符串便是
type(variable) 输出变量的类型
- 代码
# 字典的内置函数
dict01={"name":"陈平安","age":"30","sex":"男"}
print(len(dict01))
str1=str(dict01)
print(type(str1))
print(str1)
结果:

字典的内置方法
dict.clear() 删除字典中所有的元素
dict.copy() 返回一个字典的浅复制
dict.fromkeys(seq,val) 创建一个新字典,以序列seq中元素做字典的键,val作为所有键的值,不写,默认为None
dict.get(key,default=None) 返回指定键的值,如果键不在字典中返回default设置的值
key in dict:判断键是否在字典中
dict.items() 以列表返回一个视图对象
格式:dict_items([('name', '陈平安'), ('age', '30'), ('sex', '男')])
dict.keys() 返回一个视图对象
格式:dict_keys(['name', 'age', 'sex'])
dict.values() 返回一个视图对象
格式:dict_values(['陈平安', '30', '男', '剑客'])
dict.setdefault(key,default=None) 通过键获取值,如果值不存在就添加到字典中
dict.update(dict2) 把字典dict2的键值对更新到dict中
popitem() 返回并删除字典中的最后一对键和值
直接赋值和浅拷贝的区别
直接赋值相当于给对象起个别名,多个引用指向同一个对象。、
浅拷贝相当于重新创建了一个对象。
- 代码
# 直接赋值和copy的区别
dict1={"name":"陈平安","age":"30","sex":"男"}
dict2=dict1 # 浅拷贝:引用对象,多个引用指向同一个对象
dict3=dict1.copy() # 浅拷贝:深拷贝负对象(一级目录),子对象(二级目录)不拷贝,子对象是引用
print(id(dict1)) # 2895704541056
print(id(dict2)) # 2895704541056
print(id(dict3)) # 2895704763008
# 发现 直接赋值的内存地址一样,通过copy浅拷贝的内存地址不一样,所以dict3的值不会随着dict1的修改而更改
# 修改data数据
dict1["name"]="崔东山"
print(dict1)
print(dict2)
print(dict3)
结果:

集合(set)
集合(set)是一个无序的不重复元素序列
特点
- 无序
- 元素不重复
- 可变
创建集合
set={value1,value2,value3,...}
或者
set(value)
集合的基本操作
添加元素
将元素x添加到s集合中,如果集合已存在,则不进行任何操作
s.add(x)
将元素x添加到s集合中,且参数可以是列表,元组,字典
s.update(x)
- 代码
# 集合
set1={1,2,3,4,5,"hah","陈平安"}
print(set1)
set1.add("宁姚") # 添加一个元素
print(set1)
list1=["hello","a","b",44] # 列表
tup1=("world",2,3,"tupl") # 元组
dict1={"name":"崔东山","age":"12"} # 字典
set1.update(list1) # 添加集合
print(set1)
set1.update(tup1) # 添加元组
print(set1)
set1.update(dict1) # 添加字典
print(set1)
结果:

移除元素
将元素x从集合s中移除,如果元素不存在,则会发生错误
s.remove(x)
将元素x从集合s中移除,如果元素不存在,则不会发生错误
s.discard(x)
随机删除集合中的一个元素,并且返回被删除的元素
s.pop()
计算集合元素个数
len(s)
清空集合
s.clear()
判断元素是否在集合中存在
x in s
集合的内置方法
add() 为集合添加元素
clear() 移除集合中的所有元素
copy() 拷贝一个集合
difference() 返回多个集合的差集
difference_update() 移除集合中的元素,该元素在指定的集合也存在。
discard() 删除集合中指定的元素
intersection() 返回集合的交集
intersection_update() 返回集合的交集。
isdisjoint() 判断两个集合是否包含相同的元素,如果没有返回 True,否则返回 False。
issubset() 判断指定集合是否为该方法参数集合的子集。
issuperset() 判断该方法的参数集合是否为指定集合的子集
pop() 随机移除元素
remove() 移除指定元素
symmetric_difference()返回两个集合中不重复的元素集合。
symmetric_difference_update() 移除当前集合中在另外一个指定集合相同的元素,并将另外一个指定集合中不同的元素插入到当前集合中。
union() 返回两个集合的并集
update() 给集合添加元素
错误
AttributeError属性错误
"jfi".isnumeric()
TypeError类型错误
seq1=(123,"3340","str")
print("-".join(seq1))

浙公网安备 33010602011771号