直接find干就完了。
如果你希望找到字符串中所有子串出現的位置,而不僅僅是一個位置,你可以通過循環查找并收集所有起始位置。以下是修改后的代碼:
def find_all_substring_positions(string, substring):
? ? positions = [] ?# 用于存儲所有匹配子串的起始位置
? ? start = 0 ?# 初始化起始搜索位置
? ? while start < len(string):
? ? ? ? position = string.find(substring, start) ?# 從start位置開始查找
? ? ? ? if position == -1: ?# 如果找不到子串,則結束循環
? ? ? ? ? ? break
? ? ? ? positions.append(position) ?# 存儲找到的位置
? ? ? ? start = position + 1 ?# 更新起始搜索位置到當前找到子串的下一個字符
? ? return positions if positions else -1 ?# 如果找到了位置,返回positions列表,否則返回-1
# 示例使用
string_example = "hello world, hello again, hello there"
substring_example = "hello"
print(find_all_substring_positions(string_example, substring_example))
這段代碼會返回一個列表,其中包含
substring
在
string
中出現的所有起始位置。如果沒有找到子串,則返回-1。