在Python中(zhong),何字我们可以使用内置的符串字符串方法来查找子字符串,以下是查找一些常用的字符串查找方(fang)法:(图片来源网络,侵删)
1、何字str.find(sub[,符串 start[, end]])

2、str.index(sub[,查找 start[, end]])

3、str.count(sub[,何字 start[, end]])

4、str.startswith(prefix[,符串 start[, end]])
5、str.endswith(suffix[,查找 start[, end]])
6、str.lower()
7、何字str.upper()
8、符串str.replace(old,查找 new[, count])
1、str.find(sub[,何字 start[, end]])
此方法返回子字符串在字符串中首次出现的最小索引,如果未找到则(ze)返回1,符串可选参数start和end用于指定搜索的查找起始和结束位置。
“`python
text = "Hello, world!"
print(text.find("world")) # 输出: 7
print(text.find("world", 8)) # 输出: 1
“`
2、str.index(sub[, start[, end]])
此方法(fa)与str.find()类似,但如果(guo)未找到子字符串,则会引发ValueError异常。
“`python
text = "Hello, world!"
print(text.index("world", 8)) # 抛出异常: ValueError: substring not found
“`
3、str.count(sub[, start[, end]])
此方(fang)法返回子字符串在字符串中出现(xian)的次数,可选参数start和end用于指(zhi)定搜索的起始和(he)结束位置。
“`python
text = "Hello, world! The world is beautiful."
print(text.count("world")) # 输出: 2
“`
4、str.startswith(prefix[, start[, end]])
此方法检查字符串是否以指定的前缀开头,可选参数start和end用(yong)于指定搜索的起始和结束(shu)位置。
“`python
text = "Hello, world!"
print(text.startswith("Hello")) # 输出: True
“`
5、str.endswith(suffix[, start[, end]])
此方法(fa)检查字符串是否以指定的后缀结尾,可选参数start和end用于指定搜索的(de)起始和结束位置。
“`python
text = "Hello, world!"
print(text.endswith("!")) # 输出: True
“`
6、str.lower()
此方法返回字符串的小写版本。
“`python
text = "Hello, World!"
“`
7、str.upper()
此方法(fa)返回字符串的大写版本。
“`python
text = "Hello, World!"
print(text.upper()) # 输出(chu): "HELLO, WORLD!"
“`
8、str.replace(old, new[, count])
此方(fang)法返回一个新(xin)的(de)字符串,其中(zhong)所有出现的旧子字符串都被新子字符串替换,可选参数count用于指定最大替换次数。
“`python
text = "Hello, world!"
print(text.replace("world", "Earth")) # 输出: "Hello, Earth!"
“`




