我有一个函数,它接受一个参数字符串和一个'目标',其中目标是字符串的子字符串。我需要在字符串中输出这些子字符串的索引。我不允许使用split函数,那么我该如何分割字符串呢?例:如果字符串是"我们不需要没有教育我们不需要思想控制我们dont"目标是"不要"输出将是:[1,6,13]
目标也可以是'we don ',所以我不能在每个空间都分割。
我有这个,它输出字符串中的每个字符,虽然我不确定为什么它不输出只是'不'三次:
#
def position(string, target):
output = []
for target in string:
output.append(target)
return output
print(position('we dont need no education we dont need no thought control no we dont', 'dont'))
#
我想过把字符串放入列表中,但这行不通,因为它会消除使用"我们不"作为目标的能力。只是不确定如何计算目标字符的实例数与字符串字符的实例数相比较,然后能够输出目标在字符串中的位置。经过编辑澄清,希望能有所帮助。
也很确定我不允许使用。find()
这符合要求吗?
example_str = "we dont need no education we dont need no thought control no we dont"
key = "dont"
count = []
word_count = 0
for i in range(len(example_str)):
if example_str[i] == " ":
word_count += 1
if example_str.startswith(key, i):
count.append(word_count)
print(count)
给输出
[1, 6, 13]
此解决方案不仅适用于单个单词,而且适用于任何类型的子字符串。
返回什么?
以单词为单位的匹配索引列表
def doIt(text: str, subs: str):
indices = []
prev = 0
for i in range(len(text)):
indices.append(prev)
if text[i] == " " and (i < len(text) - 1 and text[i + 1] != " "):
prev += 1
matches = []
left, right = 0, len(text)
while left <= right:
try:
ind = text.index(subs, left, right)
matches.append(indices[ind])
left = ind + 1
except:
break
return matches
测试text = "we dont need no education we dont need no thought control no we dont"
subs = "we dont"
print(doIt(text, subs))
输出def doIt(text: str, subs: str):
indices = []
prev = 0
for i in range(len(text)):
indices.append(prev)
if text[i] == " " and (i < len(text) - 1 and text[i + 1] != " "):
prev += 1
matches = []
left, right = 0, len(text)
while left <= right:
try:
ind = text.index(subs, left, right)
matches.append(indices[ind])
left = ind + 1
except:
break
return matches
text = "we dont need no education we dont need no thought control no we dont"
subs = "we dont"
print(doIt(text, subs))
[0, 5, 12]