字符串常见操作
学习目标:
- 掌握查找方法find(),index()
- 掌握修改方法replace(),split()
1. 查找--find(),index()
所谓字符串查找方法即是查找子串在字符串中的位置或出现的次数。
find():检测某个子串是否包含在这个字符串中,如果在返回这个子串开始的位置下标,否则则返回-1。
语法
字符串序列.find(子串, 开始位置下标, 结束位置下标)
注意:开始和结束位置下标可以省略,表示在整个字符串序列中查找。
- 快速体验
mystr = "hello world and itcast and itheima and Python"
print(mystr.find('and')) # 12
print(mystr.find('and', 15, 30)) # 23
print(mystr.find('ands')) # -1
index():检测某个子串是否包含在这个字符串中,如果在返回这个子串开始的位置下标,否则则报异常。
语法
字符串序列.index(子串, 开始位置下标, 结束位置下标)
注意:开始和结束位置下标可以省略,表示在整个字符串序列中查找。
- 快速体验
mystr = "hello world and itcast and itheima and Python"
print(mystr.index('and')) # 12
print(mystr.index('and', 15, 30)) # 23
print(mystr.index('ands')) # 报错
2. 修改--replace(),split()
所谓修改字符串,指的就是通过函数的形式修改字符串中的数据。
replace():替换
语法
字符串序列.replace(旧子串, 新子串, 替换次数)
注意:替换次数如果查出子串出现次数,则替换次数为该子串出现次数。
- 快速体验
mystr = "hello world and itcast and itheima and Python"
# 结果:hello world he itcast he itheima he Python
print(mystr.replace('and', 'he'))
# 结果:hello world he itcast he itheima he Python
print(mystr.replace('and', 'he', 10))
# 结果:hello world and itcast and itheima and Python
print(mystr)
注意:数据按照是否能直接修改分为==可变类型==和==不可变类型==两种。字符串类型的数据修改的时候不能改变原有字符串,属于不能直接修改数据的类型即是不可变类型。
split():按照指定字符分割字符串。
语法
字符串序列.split(分割字符, num)
注意:num表示的是分割字符出现的次数,即将来返回数据个数为num+1个。
- 快速体验
mystr = "hello world and itcast and itheima and Python"
# 结果:['hello world ', ' itcast ', ' itheima ', ' Python']
print(mystr.split('and'))
# 结果:['hello world ', ' itcast ', ' itheima and Python']
print(mystr.split('and', 2))
# 结果:['hello', 'world', 'and', 'itcast', 'and', 'itheima', 'and', 'Python']
print(mystr.split(' '))
# 结果:['hello', 'world', 'and itcast and itheima and Python']
print(mystr.split(' ', 2))
注意:如果分割字符是原有字符串中的子串,分割后则丢失该子串。
3. 小结
常用查找操作方法
- find()
- index()
常用修改操作方法
- replace()
- split()