10.编写一个Python程序,输入一个字符串和一个子字符串,输出子字符串在原字符串中的位置。运用input
时间: 2025-03-30 21:11:56 浏览: 37
### 查找子字符串在主字符串中的位置
要实现一个用于查找子字符串在主字符串中位置的 Python 程序,可以利用内置函数 `str.find()` 或者正则表达式的功能。以下是基于输入函数的一个简单实现:
#### 使用 `find` 方法
`str.find(substring)` 是一种高效的方法,它返回子字符串首次出现的位置索引;如果未找到,则返回 `-1`。
```python
def find_substring_position(main_string, sub_string):
position = main_string.find(sub_string)
if position != -1:
return f"The substring '{sub_string}' starts at index {position}."[^1]
else:
return "The substring was not found."
main_input = input("Enter the main string: ")
sub_input = input("Enter the substring you want to search for: ")
result = find_substring_position(main_input, sub_input)
print(result)
```
上述代码通过用户输入获取主字符串和目标子字符串,并调用 `find` 函数定位子字符串第一次出现的位置。
#### 处理多次匹配的情况
如果需要找出所有匹配项的位置,可以通过循环逐步扫描整个字符串并记录每次发现的位置。
```python
def all_positions_of_substring(main_string, sub_string):
start = 0
positions = []
while True:
pos = main_string.find(sub_string, start)
if pos == -1:
break
positions.append(pos)
start = pos + 1
if positions:
return f"All occurrences of '{sub_string}' are located at indices: {positions}."
else:
return "No occurrence of the substring was found."
main_input = input("Enter the main string: ")
sub_input = input("Enter the substring you want to search for: ")
output = all_positions_of_substring(main_input, sub_input)
print(output)
```
此版本不仅能够检测到第一个实例,还能捕捉后续所有的匹配情况,并将其存储在一个列表中以便进一步处理。
#### 正则表达式方法 (re module)
对于更复杂的模式匹配需求,可采用正则表达式库 `re` 来完成相同任务。
```python
import re
def regex_find_all_positions(main_string, pattern):
matches = [(m.start(), m.end()) for m in re.finditer(pattern, main_string)]
if matches:
return f"Pattern '{pattern}' matched from these ranges: {matches}."[^2]
else:
return "No match found with given pattern."
main_str = input("Provide your base text here:")
pat = input("What specific sequence do you wish to locate?")
res = regex_find_all_positions(main_str, pat)
print(res)
```
这里使用了 `re.finditer`, 它会迭代每一个非重叠的匹配对象,并提供它们各自的起始结束坐标。
---
阅读全文
相关推荐


















