python求字符串中单词出现的索引
时间: 2024-03-10 17:47:03 浏览: 95
c#字符串查找某词出现的次数及索引
5星 · 资源好评率100%
可以使用Python内置的字符串方法 `find` 或者正则表达式来求字符串中单词出现的索引。
使用 `find` 方法:
```python
s = "Hello world, welcome to Python world."
word = "world"
start_index = 0
while True:
index = s.find(word, start_index)
if index == -1:
break
print(f"{word} found at index {index}")
start_index = index + 1
```
输出:
```
world found at index 6
world found at index 28
```
使用正则表达式:
```python
import re
s = "Hello world, welcome to Python world."
word = "world"
pattern = re.compile(rf"\b{word}\b")
for match in pattern.finditer(s):
print(f"{word} found at index {match.start()}")
```
输出:
```
world found at index 6
world found at index 28
```
阅读全文