Python在函数中查找给定分隔符之间的字符串

时间:2018-03-22 21:04:17

标签: python-3.x

我正在checkio.org上开展这个游戏。它是一个python游戏,这个级别我需要找到两个定义的分隔符之间的单词。该函数调用它们。到目前为止,我做得还不错,但我无法从谷歌那里获得更多帮助,因为我不知道如何询问我需要什么。

无论如何我被卡住了,我想知道我在哪里搞砸了。

def between_markers(text: str, begin: str, end: str) -> str:
    """
        returns substring between two given markers
    """
    # your code here

    s = text

    #find the index for begin and end
    b = s.find(begin) + len(begin)
    c = s.find(end,b)
    #if there is a beginning delimiter return string from between
    if begin in s:
        return s[b:c]
    # if the begin is not the only return until end delimiter
    elif begin not in s:
        return s[:-c]
    #if the ending delimiter isnt there return from beinning to end of string
    elif end not in s:
        return s[b:]
    #if both delimiters are missing just return the text
    elif begin or end not in s:
        return s



if __name__ == '__main__':
    #    print('Example:')
    #    print(between_markers('What is >apple<', '>', '<'))

    # These "asserts" are used for self-checking and not for testing
    assert between_markers('What is >apple<', '>', '<') == "apple", "One sym"
    assert between_markers("<head><title>My new site</title></head>",
                                 "<title>", "</title>") == "My new site", "HTML"
    assert between_markers('No[/b] hi', '[b]', '[/b]') == 'No', 'No opened'
    assert between_markers('No [b]hi', '[b]', '[/b]') == 'hi', 'No close'
    assert between_markers('No hi', '[b]', '[/b]') == 'No hi', 'No markers at all'
    assert between_markers('No <hi>', '>', '<') == '', 'Wrong direction'
    print('Wow, you are doing pretty good. Time to check it!')

我被困在这里想知道我哪里错了。

elif begin not in s: return s[:c]:它会下地狱。理论上return s[:c]应该返回c之前的所有内容,但它会在字符串结尾之前切掉一个字母,而我使用的每一个切片都会将其切掉一个字符。这个assert between_markers('No [b]hi', '[b]', '[/b]') == 'hi', 'No close'给了我h而非hi。在先前的断言中使用[:-c]使我失败...

欢迎提出任何指示。

2 个答案:

答案 0 :(得分:0)

切片的效果与您认为的不同:

s = "012345"
p = s[1:3] 
print(p)

打印

12

1 包含切换到3 独占

如果找不到任何内容,

str.find()将返回-1。如果您将begin的长度添加到-1(未找到开始),然后从此位置开始查找end,则会出现逻辑错误。根据文本和标记,您会收到错误。

如果你没有立即将begin-tag的长度添加到find标记的(可能)-1结果中,你可以使你的比较更容易处理。

def between_markers(text: str, begin: str, end: str) -> str:
    """ returns substring between two given markers """  
    s = text

    #find the index for begin and end
    b = s.find(begin)                # -1 if not found
    c = s.find(end, b+len(begin))    # search only after begins match, -1 if not found

    if b > -1 and b < c:             # both found, b before c (not strictly needed) as                         
        return s[b+len(begin):c]     # c is always "after" b - makes more sense 2 me

    elif b == -1 and c > -1:         # only c found
        return s[:c]

    elif b > -1 and c == -1:         # only b found
        return s[b+len(begin):]

    else:                            # none found
        return s

传递你自己写的断言。

答案 1 :(得分:0)

这是嵌套if b > 5的hackey,但它可以正常工作

def between_markers(text: str, begin: str, end: str) -> str:
s = text

# find the index for begin and end
b = s.find(begin)  # -1 if not found
c = s.find(end, b + len(begin))  # search only after begins match, -1 if not found

    if b != -1 and c == -1:   # only b found
        if b > 5:
            return ""
        else:
            return s[b + len(begin):]

    if b == -1 and c == -1:   # neither found
        return s

    if b != -1 and c != -1:     # both found
        return s[b + len(begin):c]

    if b == -1 and c != -1:   # only c found
        return s[:c]

    else:  # none found
        return ""