在 Python 中,可以通过循环结合如find()
方法或使用列表推导式来获取字符串中某个字符的所有位置。常见的方法如下:
方法1:循环结合 find()
方法
通过循环调用 find()
方法,每次从上一次找到的位置之后继续查找,直到返回 -1
。
eg:
text = "applepenapple"
char = "p"
positions = []
start = 0
while True:
pos = text.find(char, start)
if pos == -1:
break
positions.append(pos)
start = pos + 1 # 从找到的位置之后继续查找
print(positions) # 输出:[1, 2, 5, 9, 10]
⭐方法2:列表推导式
使用列表推导式结合 enumerate()
函数,遍历字符串的每个字符及其索引,筛选出目标字符的所有位置。
eg:
text = "applepenapple"
char = "p"
positions = [i for i, c in enumerate(text) if c == char]
print(positions) # 输出:[1, 2, 5, 9, 10]
方法3:正则表达式
如果需要更通用的解决方案,可以使用正则表达式模块 re
来查找所有匹配的位置。
eg:
import re
text = "applepenapple"
char = "p"
# 使用正则表达式查找所有匹配的位置
positions = [m.start() for m in re.finditer(char, text)]
print(positions) # 输出:[1, 2, 5, 9, 10]
方法4:使用 str.index()
和循环
与 find()
类似,str.index()
也可以用来查找字符的位置,但它会在找不到字符时抛出异常。可以通过捕获异常来处理这种情况。
eg:
text = "applepenapple"
char = "p"
positions = []
start = 0
while True:
try:
pos = text.index(char, start)
positions.append(pos)
start = pos + 1
except ValueError:
break
print(positions) # 输出:[1, 2, 5, 9, 10]