在Python中,我们可以使用内置的字符串方法来查找子字符串,以下是一些常用的字符串查找方法:,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]])
,此方法返回子字符串在字符串中首次出现的最小索引,如果未找到则返回1,可选参数start
和end
用于指定搜索的起始和结束位置。,“`python,text = “Hello, world!”,print(text.find(“world”)) # 输出: 7,print(text.find(“world”, 8)) # 输出: 1,“`,2、str.index(sub[, start[, end]])
,此方法与str.find()
类似,但如果未找到子字符串,则会引发ValueError
异常。,“`python,text = “Hello, world!”,print(text.index(“world”)) # 输出: 7,print(text.index(“world”, 8)) # 抛出异常: ValueError: substring not found,“`,3、str.count(sub[, start[, end]])
,此方法返回子字符串在字符串中出现的次数,可选参数start
和end
用于指定搜索的起始和结束位置。,“`python,text = “Hello, world! The world is beautiful.”,print(text.count(“world”)) # 输出: 2,“`,4、str.startswith(prefix[, start[, end]])
,此方法检查字符串是否以指定的前缀开头,可选参数start
和end
用于指定搜索的起始和结束位置。,“`python,text = “Hello, world!”,print(text.startswith(“Hello”)) # 输出: True,print(text.startswith(“world”, 7)) # 输出: False,“`,5、str.endswith(suffix[, start[, end]])
,此方法检查字符串是否以指定的后缀结尾,可选参数start
和end
用于指定搜索的起始和结束位置。,“`python,text = “Hello, world!”,print(text.endswith(“!”)) # 输出: True,print(text.endswith(“world”, 0, 5)) # 输出: False,“`,6、str.lower()
,此方法返回字符串的小写版本。,“`python,text = “Hello, World!”,print(text.lower()) # 输出: “hello, world!”,“`,7、str.upper()
,此方法返回字符串的大写版本。,“`python,text = “Hello, World!”,print(text.upper()) # 输出: “HELLO, WORLD!”,“`,8、str.replace(old, new[, count])
,此方法返回一个新的字符串,其中所有出现的旧子字符串都被新子字符串替换,可选参数count
用于指定最大替换次数。,“`python,text = “Hello, world!”,print(text.replace(“world”, “Earth”)) # 输出: “Hello, Earth!”,“`, ,
原创文章,作者:admin,如若转载,请注明出处:https://www.vaicdn.com/news/59940.html