使用字符串中的内建函数查找一个字符串在另外一个字符串指定范围中首次和最后一次出现的位置
时间: 2024-05-05 15:19:39 浏览: 15
您可以使用字符串中的 find 和 rfind 函数来查找一个字符串在另外一个字符串指定范围中首次和最后一次出现的位置。find 是从左侧开始查找,而 rfind 是从右侧开始查找。例如,以下代码可以查找一个字符串在另一个字符串中首次和最后一次出现的位置:
```
string = "Hello, World!"
substring = "o"
start_index = 2
end_index = 9
# find the first occurrence of the substring in the range
first_index = string.find(substring, start_index, end_index)
print("The first occurrence is at index:", first_index)
# find the last occurrence of the substring in the range
last_index = string.rfind(substring, start_index, end_index)
print("The last occurrence is at index:", last_index)
```
在这个例子中,我们在字符串 "Hello, World!" 的范围内(从第三个字符 "l" 开始,到第十个字符 "l" 结束),查找字符串 "o" 的首次和最后一次出现的位置。输出如下:
```
The first occurrence is at index: 4
The last occurrence is at index: 7
```