checkio练习题:between-markers

You are given a string and two markers (the initial and final). You have to find a substring enclosed between these two markers. 
But there are a few important conditions:

The initial and final markers are always different.
If there is no initial marker then the beginning should be considered as the beginning of a string.
If there is no final marker then the ending should be considered as the ending of a string.
If the initial and final markers are missing then simply return the whole string.
If the final marker is standing in front of the initial one then return an empty string.
Input: Three arguments. All of them are strings. The second and third arguments are the initial and final markers.

Output: A string.

Example:

between_markers('What is >apple<', '>', '<') == 'apple'
between_markers('No[/b] hi', '[b]', '[/b]') == 'No'
1
2
How it is used: for parsing texts

Precondition: can't be more than one final marker and can't be more than one initial
    
给你一个字符串和两个标记(初始和最终)。你必须找到这两个标记之间的子串。
但是有一些重要的条件:初始和最终标记总是不同的。
如果没有初始标记,则应将开头视为字符串的开头。
如果没有最终标记,那么结尾应该被视为字符串的结尾。
如果缺少初始和最终标记,则只返回整个字符串。
如果最终标记位于初始标记的前面,则返回空字符串。

输入:三个参数。所有这些都是字符串。第二个和第三个参数是初始和最终标记。
输出:一个字符串。

 

 

import re


def between_markers(text: str, begin: str, end: str) -> str:
    """
        returns substring between two given markers
    """
    try:
        start = text.index(begin) + len(begin)
    except ValueError:
        start = 0
    try:
        finish = text.index(end)
    except ValueError:
        finish = len(text)

    return text[start:finish]


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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值