目录
----分割线----
一、字符串操作
1、切分字符串
split():按照指定字符分割字符串
【演示】
mystr = "hello world and hello and java and Python"
print(mystr.split('and'))
2、字符串连接
join():⽤⼀个字符或子串合并字符串,即是将多个字符串合并为⼀个新的字符串。
【演示】
t1 = ('aa', 'b', 'cc', 'ddd')
print('...'.join(t1))
3、删除两边空格
strip():删除字符串两侧空⽩字符。
【演示】
mystr=' hello python '
print(len(mystr))
print(len(mystr.strip()))
4、判断
startswith():检查字符串是否是以指定⼦串开头,是则返回 True,否则返回 False。如果设置开 始和结束位置下标,则在指定范围内检查。
mystr = "hello world and itcast and itheima and Python "
print(mystr.startswith('hello'))
print(mystr.startswith('hello', 5, 20))
二、列表
列表本质上是一个序列,列表可以一次存储多个数据
【演示】
name_list = ["James", "蔡徐坤", "罗志祥", "格林", 2022]
三、列表的常用操作
1、增删改查操作
增:append():列表结尾追加数据。
【演示】
name_list = ['Tom', 'Lily', 'Rose']
name_list.append('xiaoming')
print(name_list)
删:del ⽬标
【演示】
name_list = ['Tom', 'Lily', 'Rose']
del name_list
print(name_list)
改:修改指定下标数据,只需给该数据重新赋值即可。
【演示】
name_list = ['Tom', 'Lily', 'Rose']
name_list[0] = 'aaa'
print(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))
2、统计
count():统计指定数据在当前列表中出现的次数。
name_list2 = ["a", "b", "c", "d"]
result1 = name_list2.count("c")
result2 = name_list2.count("d")
result3 = name_list2.count("b")
print(result1, result2, result3)
3、列表长度
len():访问列表⻓度,即列表中数据的个数。
name_list = ['Tom', 'Lily', 'Rose']
print(len(name_list))
4、判断指定元素是否存在
in:判断指定数据在某个列表序列,如果在返回True,否则返回False
name_list = ['Tom', 'Lily', 'Rose']
print('Lily' in name_list)
print('Lilys' in name_list)
not in:判断指定数据不在某个列表序列,如果不在返回True,否则返回False
name_list = ['Tom', 'Lily', 'Rose']
print('Lily' not in name_list)
print('Lilys' not in name_list)
5、复制列表
copy():数组的复制使用的copy函数。
【演示】
name_list = ['Tom', 'Lily', 'Rose']
name_li2 = name_list.copy()
# 结果:['Tom', 'Lily', 'Rose']
print(name_li2)
6、排序
sort():升序排序
sort(reverse=True):降序排序
score_list = [35, 89, 77, 0]
score_list.sort()
print(score_list)
score_list.sort(reverse=True)
print(score_list)
7、列表循环
while循环列表,可以用len()得到列表的长度,根据长度循环列表
【演示】
country_list = ["乌克兰", "俄罗斯", "漂亮国", "中国"]
i = 0
while i < len(country_list):
print(i, country_list[i])
i += 1
for循环列表
country_list = ["乌克兰", "俄罗斯", "漂亮国", "中国"]
for j in country_list:
print(j)
8、切片
切片是指对操作的对象截取其中⼀部分的操作。字符串、列表、元组都支持切⽚操作
【演示】
name = "abcdefg"
print(name[2:5:1])
print(name[2:5])
print(name[:5])
print(name[1:])
print(name[:])
print(name[::2])
print(name[:-1])
print(name[-4:-1])
print(name[::-1])