在字符串中查找子串
时间: 2023-09-05 19:10:32 浏览: 94
在 Python 中,可以使用字符串的 `find()` 方法来查找子串是否在原始字符串中出现。该方法返回子串在原始字符串中第一次出现的索引,如果未找到则返回 -1。
例如:
```python
string = "Hello World"
substring = "World"
index = string.find(substring)
if index != -1:
print("Substring found at index:", index)
else:
print("Substring not found")
```
输出:
```
Substring found at index: 6
```
如果需要查找所有出现的位置,可以使用 `while` 循环和 `find()` 方法来实现:
```python
string = "Hello World, Hello Python, Hello AI"
substring = "Hello"
index = 0
while index >= 0:
index = string.find(substring, index)
if index != -1:
print("Substring found at index:", index)
index += 1
else:
print("All substrings found")
break
```
输出:
```
Substring found at index: 0
Substring found at index: 12
Substring found at index: 24
All substrings found
```
阅读全文