python 找出全部子串位置:两个字符串s1,s2,找出s2在s1中所有出现的位置。
时间: 2023-05-26 12:04:06 浏览: 66
可以使用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中所有出现的位置。
相关问题
输入2个字符串S1和S2,要求删除字符串S1中出现的所有子串S2,即结果字符串中不能包含S2。
可以使用字符串替换的方法来实现删除字符串S1中所有出现的子串S2。具体步骤如下:
1. 使用字符串的 replace() 方法,将S1中所有的S2替换为空字符串 ""。
2. 返回替换后的S1字符串。
以下是 Python 代码实现:
```python
def delete_substring(s1, s2):
return s1.replace(s2, "")
```
示例:
```python
s1 = "hello world, world is beautiful"
s2 = "world"
result = delete_substring(s1, s2)
print(result) # 输出:hello , is beautiful
```
注意:该方法只能删除S1中出现的所有S2子串,无法处理S1中某些子串被S2包含的情况。例如,若S1="hello worl",S2="world",则该方法无法处理。
输入2个字符串s1和s2,要求删除s1中出现的所有子串s2,即结果字符串中不能包括s2
以下是Python代码实现:
```python
def remove_substring(s1, s2):
result = ""
i = 0
while i < len(s1):
if s1[i:i+len(s2)] == s2:
i += len(s2)
else:
result += s1[i]
i += 1
return result
```
函数`remove_substring`接受两个字符串`s1`和`s2`,并返回一个新的字符串,其中`s1`中出现的所有子串`s2`都被删除了。
函数的实现是通过遍历`s1`的每个字符,如果当前字符及其之后的字符与`s2`相同,则跳过`s2`长度的字符,否则将当前字符添加到结果字符串中。
例如,如果`s1="hello world"`,`s2="l"`,则函数将返回`heo word`。