Python中不使用find,rfind,index等内置函数如何获取一个字符串中另一个字符串第二次出现的位置
时间: 2023-05-26 12:02:04 浏览: 153
可以使用正则表达式,利用re模块中的finditer函数来找到字符串中所有匹配的子串,找到第二个匹配的位置即可。下面是一个示例代码:
```python
import re
def find_second_occurrence(string, sub_string):
matches = list(re.finditer(sub_string, string))
if len(matches) < 2:
return -1
else:
return matches[1].start()
# 示例用法
string = "hello world, hello Python"
sub_string = "hello"
print(find_second_occurrence(string, sub_string)) # 输出: 13
```
在上面的代码中,我们首先使用re模块中的finditer函数找到字符串中所有匹配的子串,然后判断匹配串的数量是否大于等于2,如果大于等于2,则返回第二个匹配串的起始位置。如果匹配串数量小于2,说明子串在原字符串中至多只出现了一次,返回-1表示未找到第二个匹配串。
相关问题
现有一个字符串“How do you do do do today?”,以及一个单词do。 请定义一个函数my_find(s,t),在不使用系统提供的find、rfind和index函数的情况下,找出t在s中第二次出现的位置索引坐标,找不到返回-1。 在上述字符串和单词传入my_find中后,结果应该是11。
以下是Python3的实现:
```python
def my_find(s, t):
first_idx = -1
second_idx = -1
for i in range(len(s)):
if s[i:i+len(t)] == t:
if first_idx == -1:
first_idx = i
elif second_idx == -1:
second_idx = i
break
return second_idx
s = "How do you do do do today?"
t = "do"
print(my_find(s, t)) # 输出 11
```
思路:遍历字符串s,找到t出现的位置。当第一次出现时,记录下位置。当第二次出现时,记录下位置并跳出循环。最后返回第二次出现的位置。如果找不到第二次出现位置,则返回默认值-1。
python中的find和rfind
python中的find和rfind是字符串的查找函数。find返回在字符串中第一个匹配子串的位置,rfind返回在字符串中最后一个匹配子串的位置。两者的区别在于搜索方向的不同:find从左向右搜索,而rfind从右向左搜索。
阅读全文
相关推荐
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)