为了账号安全,请及时绑定邮箱和手机立即绑定

无法弄清楚代码有什么问题。尝试替代 string.find()

无法弄清楚代码有什么问题。尝试替代 string.find()

慕码人2483693 2022-11-18 20:54:27
当我尝试打印变量 indA、indB 或字符串时,它似乎可以工作。输入两个字母和一个单词,如果单词中存在字母,则打印两个字母之间的字符。def substring_between_letters(word, start, end):  for index in range(len(word)):    if word[index] == start:      indA = index      break      return indA    if word[index] == end:      indB = index      break      return indB      string = word[indA + 1 : indB]    else:      string = word  return string 
查看完整描述

1 回答

?
米脂

TA贡献1836条经验 获得超3个赞

这应该工作:


def substring_between_letters(word, start, end):

    hasA = False # Checks if start has already been found

    for index in range(len(word)):

        if word[index] == start:

            hasA = True

            aIndex = index

        if hasA and word[index] == end:

            bIndex = index

            return word[aIndex: bIndex + 1]

    return word # If substring could not be found

例如:


>>> print(substring_between_letters("hello everyone!", "l", "e"))

lo e

您的代码存在的问题包括:

  • 可以定义break导致循环退出的语句。string编写此函数的更好方法实际上是放弃break语句。

  • 返回 indA 和 indB 会导致函数的输出只是一个整数。

  • for循环中不需要else语句。简单地word在函数末尾返回并string在循环内返回正确的值更清晰,计算速度更快。

  • 您编写的代码没有捕获以确保end出现在start. 如果该end字符出现在该start字符之后,则 indA 将不会被定义,您将得到一个错误。

此外,看起来这段代码会为您提供第一个实例,其中 s 子字符串以字符“start”开头并以字符“end”结尾。但是,在 中str.find(sub, start, end),“开始”和“结束”定义了要str在其中搜索的子字符串sub。如果您正在模拟str.find(),则需要四个参数:一个要从中搜索的字符串 (str)、一个要搜索的子字符串 (sub)、一个起始整数 (start) 来定义在 str 中开始搜索的位置,以及一个结束整数 (end ) 来定义在 str 中停止搜索的位置。


查看完整回答
反对 回复 2022-11-18
  • 1 回答
  • 0 关注
  • 59 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信