ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

【py.checkio】【HOME】Between Markers

2021-12-25 15:05:27  阅读:274  来源: 互联网

标签:begin py end text checkio markers str between HOME


题目:在text中找出begin,end之间的子字符串;

我的代码:

def between_markers(text: str, begin: str, end: str) -> str:
    """
        returns substring between two given markers
    """
    # your code here
    if begin not in text and end not in text:
        return text
    elif begin not in text:
        e = text.index(end)
        return text[:e]
    elif end not in text:
        b = text.index(begin)
        return text[b+len(begin):]
    else:
        b = text.index(begin)
        e = text.index(end)
        if b < e:
            return text[b+len(begin):e]
        else:
            return ''

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

Best "Clear" Solution(最佳"清晰"解决方案):

def between_markers(text: str, begin: str, end: str) -> str:
    start = text.find(begin) + len(begin) if begin in text else None
    stop = text.find(end) if end in text else None
    return text[start:stop]

Best "Creative" Solution(最佳"创意"解决方案):

def between_markers(txt, begin, end):
    a, b, c = txt.find(begin), txt.find(end), len(begin)
    return [txt[a+c:b], txt[a+c:], txt[:b], txt][2*(a<0)+(b<0)]

text.find(str, beg=0, end=len(string)):检测text字符串中是否包含子字符串str,如果指定beg和end范围,则检查是否包含在指定范围内,如果包含子字符串返回开始的索引值,否则返回-1。 

Best "Speedy" Solution(最佳"快速"解决方案):

between_markers = lambda text, begin, end: text[text.index(begin)+len(begin) if begin in text else 0: text.index(end) if end in text else len(text)]

标签:begin,py,end,text,checkio,markers,str,between,HOME
来源: https://blog.csdn.net/m0_37586703/article/details/122143431

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有