1. 数据容器:tuple(元组)
(1)定义
t1 = (1, "Hello", True)
t2 = ()
t3 = tuple()
print(f"t1的类型是:{type(t1)},内容是:{t1}")
print(f"t2的类型是:{type(t2)},内容是:{t2}")
print(f"t3的类型是:{type(t3)},内容是:{t3}")
运行结果:
(2)定义单个元素的元素
t1 = ("hello")
print(f"t1的类型是{type(t1)},内容是:{t1}")
t2 = ("hello",)
print(f"t2的类型是{type(t2)},内容是:{t2}")
运行结果:
(3)元组的嵌套
t1 = ((1, 2, 3),(4, 5, 6))
print(t1[0][0])
print(t1[0][1])
print(t1[0][2])
print(t1[1][0])
print(t1[1][1])
print(t1[1][2])
运行结果:
(4)元组的操作:index查找方法
(5)元组的操作:count统计方法
(6)元组的操作:len获取长度
t1 = (1, 2, 3, 'hello', 3.4, 3, 6)
print(t1[2])
# index()
print(f"3.4在t1中的下标是:{t1.index(3.4)}")
# count()
print(f"3在t1中出现的次数是:{t1.count(3)}")
# len()
print(f"t1的长度是:{len(t1)}")
运行结果:
(7)元组的遍历
①while
t1 = (1, 2, 3, 'hello', 3.4, 3, 6)
index = 0
while index < len(t1):
print(t1[index])
index += 1
运行结果:
②for
t1 = (1, 2, 3, 'hello', 3.4, 3, 6)
index = 0
for index in t1:
print(index)
运行结果:
(8)修改元组内容
无法修改!
t1 = (1, 2, 3, 'hello', 3.4, 3, 6)
t1[0] = 10
print(t1)
运行结果:
嵌套list:可以修改!
t1 = (1, 2, ['itheima', 'python'])
t1[2][1] = 'java'
print(t1)
运行结果:
· 练习:元组的基本操作
定义一个元组,内容是:t1 = ('周杰伦', 11, ['football', 'music']),记录的是一个学生的信息(姓名、年龄、爱好)
请通过元组的功能(方法),对其进行:
1.查询其年龄所在的下标位置
2.查询学生的姓名
3.删除学生爱好中的football
4.增加爱好:coding到爱好list内
t1 = ('周杰伦', 11, ['football', 'music'])
print(f"年龄所在的下标位置是:{t1.index(11)}")
print(f"学生的姓名是:{t1[0]}")
del t1[2][0]
print(t1)
t1[2].append('coding')
print(t1)
运行结果:
2. 数据容器:str(字符串)
(1)下标(索引)
name = "itheima"
print(name[0])
print(name[-1])
运行结果:
(2)查找下标索引值
my_str = "itcast and itheima"
print(my_str.index("and"))
运行结果:
(3)替换
my_str = "itcast and itheima"
print(my_str.replace("it", "程序"))
运行结果:
(4)分割
my_str = "hello python itheima itcast"
my_str_list = my_str.split(" ")
print(my_str)
print(my_str_list)
print(type(my_str_list))
运行结果:
(5)规整
① 去前后空格
my_str = " itheima and itcast "
new_my_str = my_str.strip()
print(new_my_str)
运行结果:
② 去前后指定字符串
my_str = "12itheima and itcast"
new_my_str = my_str.strip("12")
print(new_my_str)
运行结果:
(6)统计出现次数
my_str = "itheima and itcast"
print(my_str.count("t"))
运行结果:
(7)统计字符串长度
my_str = "itheima and itcast"
print(len(my_str))
运行结果:
· 练习:分割字符串
给定一个字符串:“itheima itcast boxuegu”
1.统计字符串内有多少个“it”字符
2.将字符串内的空格,全部替换为字符:“|”
3.并按照“|”进行字符串分割,得到列表
my_str = "itheima itcast boxuegu"
num = my_str.count("it")
print(num)
new_my_str = my_str.replace(" ", "|")
print(new_my_str)
print(new_my_str.split("|"))
运行结果:
标签:容器,index,python,t1,str,print,元组,my From: https://blog.csdn.net/m0_54447321/article/details/140235033