string
name = 'abcdef'
print(name[0]) #a
# 切片:取部分数据
print(name[0:3]) # 取 下标为0,1,2的字符 abc
print(name[2:]) # 取 下标为2开始到最后的字符 cdef
print(name[1:-1]) # 取 下标为1开始 到 最后第2个 之间的字符 bcde
查找:
- find(): 字符串序列.find(子串, 开始位置下标, 结束位置下标),有则返回索引,没有则返回-1
- index():检测某个子串是否包含在这个字符串中,如果在返回这个子串开始的位置下标,否则则报异常。
sentence = "I am quite pleased to hear that you are learning python to write program"
print(sentence.find('to')) # 19
print(sentence.find('to', 30, 60)) # 56 从某个区域内查找
print(sentence.find('tos')) # -1
print(sentence.index('to')) # 19
print(sentence.index('to', 30, 60)) # 56
print(sentence.index('tos')) # 报错
修改:
- replace(): 字符串序列.replace(旧子串, 新子串, 替换次数),如果省略或设为-1,则替换所有匹配的子串。
- split(): 字符串序列.split(分割字符, num)
sentence = "I am quite pleased to hear that you are learning python to write program"
# 结果:I am quite pleased go hear that you are learning python go write program
print(sentence.replace('to', 'go'))
# 结果:I am quite pleased go hear that you are learning python go write program
print(sentence.replace('to', 'go', 10))
# 结果:I am quite pleased to hear that you are learning python to write program
print(sentence)
# 结果:['I am quite pleased ', ' hear that you are learning python ', ' write program']
print(sentence.split('to'))
# 结果:['I am quite pleased ', ' hear that you are learning python to write program']
print(sentence.split('to', 1))
# 结果:['I', 'am', 'quite', 'pleased', 'to', 'hear', 'that', 'you', 'are', 'learning', 'python', '', 'to', 'write', 'program']
print(sentence.split(' '))
# 结果:['I', 'am', 'quite pleased to hear that you are learning python to write program']
print(sentence.split(' ', 2))
list
- 有序的集合
- 可重复
- 可变
- 可以存储任何类型的数据
- 列表是序列结构,可以进行序列结构的基本操作:索引、切片、加、乘、检查成员。
# 定义list
fruitList = ['orange','apple','banana','grape']
# 获取个数
len(fruitList)
# 访问
fruitList[0]
# 当索引超出了范围时,Python会报一个IndexError错误,所以,要确保索引不要越界,记得最后一个元素的索引是len(fruitList ) - 1
# 访问最后一个还可以使用-1
fruitList[-1]
fruitList[-2]
# 末尾添加 无返回值
fruitList.append('Adam')
# 指定位置添加 无返回值
fruitList.insert(1, 'Jack')
输出:['orange', 'Jack', 'apple', 'banana', 'grape']
# 删除末尾元素,返回值为被删除的元素
fruitList.pop()
# 删除指定位置元素,返回值为被删除的元素
fruitList.pop(1)
# 替换某个元素 直接给索引赋值
fruitList[1] = 'Sarah'
tuple
- 有序列表
- 不可变
- 可重复
- 只有1个元素的
tuple
定义时必须加一个逗号,来消除歧义 - 获取数据和
list
相同,没有删除和添加方法 - 定义一个空的
tuple
,可以写成()
fruitList = ('orange','apple','banana','grape','grape')
可变: