我不能完全完成这个功能

2024-06-25 22:42:23 发布

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

嗨,我真的很困惑在这一个,这是很难让我的一部分'我们做'。只有当我运行代码时,结果才是['Hooray', ' Finally']

def split_on_separators(original, separators):
    """ (str, str) -> list of str

    Return a list of non-empty, non-blank strings from the original string
    determined by splitting the string on any of the separators.
    separators is a string of single-character separators.

    >>> split_on_separators("Hooray! Finally, we're done.", "!,")
    ['Hooray', ' Finally', " we're done."]
    """
    #I can't make we're done .
    result = []
    string=''

    for ch in original:
        if ch in separators:
            result.append(string)
            string=''
            if '' in result:
                result.remove('')
        else:
            string+char

     return result           

Tags: oftheinrestringonresultwe
2条回答

这条线:

string+char

正在计算某个东西,但不分配它。你知道吗

请尝试以下操作:

string=string+char

或者,您可以将其缩短为使用+=速记:

string += char

这与上述内容是等价的。你知道吗

    def split_on_separators(original, separators):
      result = []
      string=''

      for index,ch in enumerate(original):
          if ch in separators or index==len(original) -1:
              result.append(string)
              string=''
              if '' in result:
                  result.remove('')
          else:
            string = string+ch

      return result

res = split_on_separators("Hooray! Finally, we're done.", "!,")
print(res)

在您的解决方案中,只测试分隔符。因此,当字符串终止时,不会发生任何事情,也不会添加最后一个字符串。您还需要测试字符串终止。你知道吗

还请注意,您没有将当前字符附加到字符串,因此最后一个字符串具有“.”。也许这就是你想要的(在我看来就像一个分隔符)

相关问题 更多 >