"# 初始化搜索起始位置start_index = # 找到所有出现 "world" 的位置whileTrue:# 调用 find() 函数查找子字符串index = my_string.find("world", start_index)# 如果找不到子字符串,则退出循环ifindex == -1:break# 打印找到的位置print("子字符串 'world' 的位置:", index)# 更新起始位置,以便下...
print(sub_string) 输出 Hello 二、搜索 Python中的字符串类提供了几种搜索方法,用于查找字符串中的子串。其中最常用的方法是find()和index()。这两个方法的作用是相同的,都是查找子串在字符串中首次出现的位置。区别在于,如果未找到子串,find()方法返回-1,而index()方法则引发一个异常。例如:my_string ...
string = "Hello, world! world is beautiful." positions = [] while True: (tab)pos = string.find("world") (tab)if pos == -1: (2tab)break (tab)positions.append(pos) print(positions) # 输出:[7, 18]判断子字符串是否存在于另一个字符串中 使用find函数返回的结果判断子字符...
str2="This is a sample string."index=str2.find("Python")print(index)# 输出:-1 1. 2. 3. 在上述示例中,字符串str2中不存在子字符串"Python"。因此,find()函数的返回值为-1。 示例3:指定起始位置和结束位置 str3="This is a sample string."index=str3.find("is",3,10)print(index)# 输出...
>>>"hello, python".find("llo")!=-1True>>>"hello, python".find("lol")!=-1False>> 3、使用 index 方法 字符串对象有一个 index 方法,可以返回指定子串在该字符串中第一次出现的索引,如果没有找到会抛出异常,因此使用时需要注意捕获。
2.1 find() 检测某个子串是否包含在这个字符串中,如果在返回这个子串开始的位置下标,否则则返回-1 【子串可以理解为字符串中一部分的字符】 语法: 字符串序列.find(子串,开始位置下标,结束位置下标) 注意: 开始和结束位置下标可以省略,表示在整个字符串序列中查找 ...
string.find(substring, start=0, end=len(string))它返回substring在string中的起始位置,如果未找到则返回-1。参数设置与高级功能 除了基本语法和返回值,find函数还支持一些参数设置和高级功能,以满足更多的需求。1. start参数:可以指定字符串中查找的起始位置 text = "Python is a scripting language."# 从第...
下面是一些使用 `find()` 函数的例子。**例1**:查找子字符串的位置 str = "Hello, world!"print(str.find("world"))输出 7 在这个例子中,`"world"`这个子字符串在主字符串 `str` 中首次出现的位置是7。**例2**:查找子字符串未找到的情况 str = "Hello, world!"print(str.find("earth"))输...
print( str.find('wc') ) #没找到,返回-1 1. 2. 3. 4. 5. 2、string.index() 检测字符串是否包含指定字符,如果包含,则返回开始的索引值;否则,抛出异常,可以通过try ——except捕获异常对字符做出相应处理。 str = 'hello world' # 'wo'在字符串中 ...