str还提供了如下常用的执行查找、替换等操作的方法。
startswith():判断字符串是否以指定子串开头。
endswith():判断字符串是否以指定子串结尾
find():查找指定子串在字符串中出现的位置,如果没有找到指定子串,则返回-1。
index():查找指定子串在字符串中出现的位置,如果没有找到指定子串,则引发 ValueError
错误。
replace():使用指定子串替换字符串中的目标子串。
详见下面的代码:
# !/usr/bin/env python# -*- coding: utf-8 -*-# @Time : 2024/01# @Author : Laopis = 'ceshilaopi think ruanjian ceshi laoshifu is a boy'#判断s是否以ceshi开头print(s.startswith('ceshi'))#判断s是否以boy结尾print(s.endswith('boy'))#查找s中出现ruanjian的位置print(s.find('ruanjian'))#查找s中出现ruanjian的位置print(s.index('ruanjian'))#从索引17查找s中出现ruanjian的位置print(s.find('ruanjian',17))#从索引17查找s中出现ruanjian的位置# print(s.index('ruanjian',17)) 会提示错误#将字符串中ceshi替换成QAprint(s.replace('ruanjian',"QA"))#将字符串中1个ceshi替换成QAprint(s.replace('ruanjian',"QA",1))