问题本身在此解释:s
是要搜索的字符串,target是要查找的子字符串。打印目标开始的每个索引。
'''Exercise to complete printLocations as described below.
Create File locations.py.'''
def printLocations(s, target):
'''
s is a string to search through, and target is the substring to look for.
Print each index where the target starts.
For example:
>>> printLocations('Here, there, everywherel', 'ere')
1
8
20
'''
repetitions = s.count(target)
# ?? add initialization
for i in range(repetitions):
# ?? add loop body lines
def main():
phrase = 'Here, there, everywhere!'
print('Phrasez', phrase)
for target in ['ere', 'er', 'e', 'eh', 'zx']:
print('finding:', target)
printLocations(phrase, target)
print('All done!')
main()
答案 0 :(得分:0)
def printLocations(s, target):
'''
s is a string to search through, and target is the substring to look for.
Print each index where the target starts.
For example:
>>> printLocations('Here, there, everywherel', 'ere')
1
8
20
'''
repetitions = s.count(target)
index = -1
for i in range(repetitions):
index = s.find(target, index+1)
print(index)
def main():
phrase = 'Here, there, everywhere!'
print('Phrasez', phrase)
for target in ['ere', 'er', 'e', 'eh', 'zx']:
print('finding:', target)
printLocations(phrase, target)
print('All done!')
main()
演示:
Phrasez Here, there, everywhere!
finding: ere
1
8
20
finding: er
1
8
15
20
finding: e
1
3
8
10
13
15
20
22
finding: eh
finding: zx
All done!
答案 1 :(得分:0)
var square = function(n) {
return n * n;
}
alert(square(5));
祝你好运向老师解释......你也可以这样做:
printLocations = lambda s, target: [m.start() for m in re.finditer(re.escape(target), s)]