序列
在python中,序列就是一组按照顺序排列的值【数据集合】,在python中,存在三种内置的序列类型:字符串、列表、元组。
序列的优点:可以支持索引和切片的操作。
索引和切片
索引
特征:第一个索引为0,指向的是左端,第一个索引为负数时,指向的是右端。
a="python" p y t h o n
对应下标 0 1 2 3 4 5
切片:(高级特性)可以根据下标来获取序列对象的任意(部分)数据
语法结构:[start:end(:step)],step即步长,默认值为1,取左不取右
for i in range(0,6):
test='python'
print('获得第'+str(i)+'个字符:%s'%test[i],end=" ")
------------------
获得第0个字符:p 获得第1个字符:y 获得第2个字符:t 获得第3个字符:h 获得第4个字符:o 获得第5个字符:n
切片
取偶数位置的字符
方法一:if…else…
datastr="hello,python"
for i in range(12):
if i%2==0:
continue
else:
print(datastr[i],end="\t")
-------------------
e l , y h n
方法二:设置步长
datastr="hello,python"
print(datastr[1:13:2])
-------------------
el,yhn
序列常用函数
capitalize() 首字母大写
upper() 把字母转化为大写
lower() 把字母转化为小写
strip() 去除字符串中的空格
lstrip() 去除左边的空格
rstrip() 去除右边的空格
a=' hello '
print(a.strip())
print(a.lstrip())
print(a.rstrip())
print(a.strip().capitalize())
-------------------
hello
hello
hello
Hello
find() 查找下标值(只返回找到的第一个对应值的下标)
iddex()与find()相似,但index找不到目标时会报错
datastr="hello,python"
print(datastr.find('o'))
print(datastr.find('v'))
print(datastr.index('o'))
--------------------
4 #找到就显示该字符在字符串中的位置
-1 #找不到会显示-1
4
startwith() 判断是否为开头
endwith() 判断是否为结尾
datastr="hello,python"
print(datastr.startswith('o'))
print(datastr.endswith('n'))
--------------------
False
True
列表
列表是python当中非常重要的数据结构,是一种有序的数据集合
特点:支持增删改查;列表中的数据是可以变化的(数据可以变化,但内存地址不变);用[ ] 来表示内边类型,数据项之间用逗号分割(数据项可以使任何类型);支持索引、切片和遍历操作。
l=[1,2,3,"hello",[4,5,6]] #列表中的元素可以使任意数据类型
print(len(l))
print(type(l))
--------------------
5
<class 'list'>
列表索引和切片
l=[1,2,3,"hello",[4,5,6]]
print(l) #完整输出
print(l[0]) #输出第0个元素
print(l[0:3]) #输出前3个元素
print(l[2:]) #输出后3个元素
print(l[::-1]) #从右输出所有元素
print(l[