【问题标题】:Print Location of a string [closed]打印字符串的位置[关闭]
【发布时间】:2016-04-01 08:35:45
【问题描述】:

问题本身在这里解释:s 是要搜索的字符串,目标是要查找的子字符串。打印目标开始的每个索引。

'''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()

【问题讨论】:

  • 能否请您在此处粘贴您的代码而不是图片?
  • 所以我已经编辑过了。怎么了?你到底想做什么?
  • @PashNeopane 您能否编辑您的问题以包含您作为 cmets 添加的其他信息? SO 希望问题能够独立存在,无需任何人阅读 cmets。
  • 你可以就家庭作业寻求帮助,但你应该一些尝试自己编写一些相关的代码。不要只是在这里转储任务描述并期望我们完成所有工作。
  • @kevinguan 请不要进行掩饰问题是作业转储这一事实的编辑。

标签: python


【解决方案1】:
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!

【讨论】:

  • @PashNeopane:已编辑,检查是否是您想要的...
  • 谢谢,我不是要复制的。我只是在学习这门语言,我读过一些不同人的不妥协的评论。但感谢凯文。由于我寒假无事可做,所以我正在学习这门语言。我非常感激。但是你能解释一下在-1初始化索引的原因吗?谢谢
  • 因为您希望第一次迭代调用s.find(target, 0)-1 + 1 == 0
【解决方案2】:
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)]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-15
    • 1970-01-01
    • 1970-01-01
    • 2013-08-29
    • 1970-01-01
    相关资源
    最近更新 更多