Python找出全部子串位置
时间: 2024-02-13 11:30:40 浏览: 44
可以使用Python中的字符串函数find()和while循环来找出全部子串位置。具体步骤如下:
1. 定义一个空列表用于存储子串位置。
2. 使用字符串函数find()查找子串在主串中的第一个出现位置,如果找到了,则将该位置加入列表中,然后继续查找下一个子串位置。
3. 如果找不到子串,则退出循环。
4. 返回子串位置列表。
下面是示例代码:
```python
def find_all_substrings(string, substring):
positions = []
start = 0
while True:
pos = string.find(substring, start)
if pos == -1:
break
positions.append(pos)
start = pos + 1
return positions
```
使用示例:
```python
string = "hello world, world is beautiful"
substring = "world"
positions = find_all_substrings(string, substring)
print(positions) # 输出 [6, 18]
```
这个函数可以找到主串中所有子串的位置,如果要找到子串出现的次数,可以使用len()函数计算子串位置列表的长度。
相关问题
python 找出全部子串位置:两个字符串s1,s2,找出s2在s1中所有出现的位置。
可以使用Python的字符串方法`find()`或者正则表达式来实现找出s2在s1中所有出现的位置。
方法一:使用字符串方法`find()`
```python
s1 = "hello world, hello python, hello java"
s2 = "hello"
pos = []
i = 0
while i < len(s1):
j = s1.find(s2, i)
if j == -1:
break
pos.append(j)
i = j + 1
print(pos) # [0, 12, 24]
```
方法二:使用正则表达式
```python
import re
s1 = "hello world, hello python, hello java"
s2 = "hello"
pos = [i.start() for i in re.finditer(s2, s1)]
print(pos) # [0, 12, 24]
```
以上两种方法均可以找出s2在s1中所有出现的位置。
jmu-python-找子串
非常感谢您的提问!关于jmu-python-找子串,您可以使用Python中的字符串搜索函数来找到子串位置。其中,可以使用find()函数和index()函数。find()函数可以在字符串中查找子串,并返回其第一次出现的位置,如果没有找到则返回-1。而index()函数与find()函数类似,但是如果没有找到子串则会抛出异常。下面是一个使用find()函数找到子串位置的示例:
```
str = "hello world"
sub_str = "world"
pos = str.find(sub_str)
if pos != -1:
print("子串'{}'在字符串'{}'中的位置是: {}".format(sub_str, str, pos))
else:
print("子串'{}'在字符串'{}'中未找到".format(sub_str, str))
```
希望这个例子能帮助您解决问题。如果您还有其他问题,可以随时问我哦~
相关推荐
![](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)
![](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)