【py.checkio】【HOME】Between Markers
作者:互联网
题目:在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