我正在尝试查找字符串中"|“的所有匹配项。
def findSectionOffsets(text):
startingPos = 0
endPos = len(text)
for position in text.find("|",startingPos, endPos):
print position
endPos = position
但我得到一个错误:
for position in text.find("|",startingPos, endPos):
TypeError: 'int' object is not iterable
发布于 2012-10-22 18:50:29
函数:
def findOccurrences(s, ch):
return [i for i, letter in enumerate(s) if letter == ch]
findOccurrences(yourString, '|')
将返回发生|
的yourString
的索引列表。
发布于 2012-10-22 18:45:01
如果您想要索引字符串中所有出现的|
字符,您可以这样做
import re
str = "aaaaaa|bbbbbb|ccccc|dddd"
indexes = [x.start() for x in re.finditer('\|', str)]
print(indexes) # <-- [6, 13, 19]
你也可以这样做
indexes = [x for x, v in enumerate(str) if v == '|']
print(indexes) # <-- [6, 13, 19]
发布于 2012-10-22 18:56:40
在这里使用正则表达式更容易;
import re
def findSectionOffsets(text):
for m in re.finditer('\|', text):
print m.start(0)
https://stackoverflow.com/questions/13009675
复制相似问题