1.字符串操作
# 切分字符串
language = "python and Java and c++ and golang and Scala"
# split 切割字符串 生成一个列表;暂时理解为一个容器 有序序列
result = language.split("and")
print(result)
# 连接序列 生成字符串 跟split 是相反的操作
lang = ["English", "Chinese", "Jananese"]
# 通过 - 连接上面的语言 形成字符串
result2 = "-".join(lang)
print(result2, type(result2))
# 3、 删除字符串两边的空格 strip
class_name = " Big Data "
print(len(class_name))
# 删除两边空格
class_name_new = class_name.strip()
print(class_name_new, len(class_name_new))
# 4、·判断一个字符串是否以指定字符串开始
mystr = "hello world"
# mystr 以hello开头 则 返回True
print(mystr.startswith("hello"))
# 不是以world开头 则返回False
print(mystr.startswith("world"))
# 以world结束 返回True
print(mystr.startswith("hello"))
# 判断在指定范围内是否以hello开始
print(mystr.startswith("hello", 3, 8))
print(mystr.startswith("lo", 3, 8))
2.列表操作
# 列表 [], 然后里面可以是任何数据类型 12. 23.6.“”, []
# 列表本质上是一个序列0 1 2 3
name_list = ["James", "蔡徐坤", "罗志祥", "格林", 2022]
# len表示列表长度
print(name_list, type(name_list), len(name_list))
# 列表索引查找
print(name_list[0])
print(name_list[1])
print(name_list[3])
print(name_list[2])
print(name_list[4])
# 使用index查找指定的数据 返回指定数据在列表中的位置
print(name_list.index("格林"))
# 在指定的列表范围内 查找格林 没有找到 则报错
# print(name_list.index("格林", 0, 2))
3.列表循环
# while 循环列表
country_list = ["乌克兰", "俄罗斯", "漂亮国", "中国"]
i = 0
while i < len(country_list):
print(i, country_list[i])
i += 1
print("==================")
# for循环 循环列表
scenery_list = ["船舶大楼", "毛家屋场", "白鹿寺", "秀峰公园"]
# 通过这个临时变量 挨个地取列表中的数据 从头取到尾 没有更多数据之后结束
for j in scenery_list:
print(j)
4.列表嵌套
# 列表嵌套 0 1 2
import random
name_list = [["鸿鸿", "伟伟"], ["天天", "顺顺"], "廖警官"]
print(name_list[0])
# 单独把伟伟取出来
print(name_list[0][1])
name_list[0].append("亮亮")
print(name_list)
5.课堂练习
练习1:
有三个办公室,但是有8位老师要过来,随机分配办公室
最后打印出 办公室有的老师
'''
# 0 1 2
office = [[], [], []]
teacher = ["A", "B", "C", "D", "E", "F", "G", "H"]
for teacher in teacher:
office_num = random.randint(0, 2)
office[office_num].append(teacher)
num = 1
for office in office:
print(f'{num}#办公室,人数:{len(office)}')
num += 1
print(office)
# for t in office:
# print(t, end=' ')
print()