python - 在Python中查找最后一个位置

标签 python

我正在学习Python,我试图在没有len()的情况下解决这个问题,但我仍然陷入困境。这是测验说明。

定义一个过程 find_last,它将作为输入 两个字符串,一个搜索字符串和一个目标字符串, 并返回搜索字符串中的最后一个位置 目标字符串出现的位置,如果存在则为 -1 没有出现。

示例:find_last('aaaa', 'a') 返回 3

确保您的程序有返回语句。

这是我的代码:

def find_last(search, target):
    target = search.find(target)
    while target:
        if target == -1:
            return target
        else:
            return target +1
    return target

谢谢。

最佳答案

您有几个错误需要修复:

  1. target 是目标字符串,而不是找到它的位置。您正在覆盖该值。
  2. 您可能需要多次调用search.find
  3. 只有在 search.find 返回 -1 时才能跳出循环。然后,您的函数应返回 search.find 返回的前一个值。

解决每个问题都会给您带来好处

def find_last(search, target):
    # Find the first occurrence of target
    pos = search.find(target)

    # If you found something, keep looking for it until you don't
    # find it again
    while pos >= 0:
        # You found target once; now look for the next occurrence
        next_pos = search.find(target, pos + 1)
        if next_pos == -1:
            # no more targets, so stop looking
            break
        pos = next_pos 
    return pos

您还可以使用return pos代替break

<小时/>

正如评论中所指出的,search.rfind(target) 已经做了你想要的事情。

关于python - 在Python中查找最后一个位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49720776/

相关文章:

python - 如何在 ModelResource django-import-export 中获取请求

python - 从返回 null 的元标记 beautifulsoup 中提取数据

python - 你如何卸载 python 包/库

python - 获取 'readable'格式的函数注释

Python blobs.BlobResult 模块导入错误

python - 如何在 python 中存储它打印到标准输出的 os.system 的返回值?

c# - C#或python用于调用C++ DLL进行硬件控制

python - conda 无法识别已安装的软件包

python - 无法使用应用程序 pythonista 在 iOS 上导入 python 文件

python - Neurolab 的 newff 示例中出现错误