打印字符串的位置

2024-10-01 11:35:44 发布

您现在位置:Python中文网/ 问答频道 /正文

问题本身在这里解释: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()

Tags: theto字符串addtargetforhereis
2条回答
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!
printLocations = lambda s, target: [m.start() for m in re.finditer(re.escape(target), s)]

祝你好运向你的老师解释。。。。你也可以这样做:

printLocation = lambda s, target: [i for i in range(len(s)) if s[i:].startswith(target)]

相关问题 更多 >