要怎么样才能用find函数找出所有的python,并记录其出现的位置,结果以列表的形式存储并输出,我的代码运行出来得不到想要的结果?
你可以使用一个循环来遍历字符串,并使用字符串的 find() 方法来查找子串的位置。如果找到了子串,就将位置添加到结果列表中。如果没有找到,则退出循环。下面是一个使用 find() 方法查找所有子串的例子:
# 定义字符串
s = "I love Python. Python is my favorite programming language."
# 定义要查找的子串
substring = "Python"
# 建立空列表,用于存储子串的位置
positions = []
# 初始化位置
pos = 0
# 循环查找子串
while True:
# 使用find()方法查找子串
pos = s.find(substring, pos)
# 如果找到了子串
if pos >= 0:
# 将位置添加到结果列表中
positions.append(pos)
# 将位置后移一位
pos += 1
# 如果没有找到子串
else:
# 退出循环
break
# 输出结果
print(positions) # 输出[7, 26]