版权声明:欢迎联系我转载!欢迎交流分享!转载和分享请注明出处! https://blog.csdn.net/u014303046/article/details/82526230
Between markers
一、问题描述
要求:给定一个字符串以及两个标记(开始和结束标记),要求找到字符串中两个标记之间的子串。
注意:
- 开始和结束标记不同
- 如果没有开始标记,默认从字符串第一个字符开始
- 如果没有结束标记,默认字符串最后一位为结束
- 如果开始和结束标记都没有,则返回整个字符串
- 如果结束标记在开始标记之前,返回空字符串
输入:字符串、开始标记和结束标记
输出:字符串
示例:
between_markers('What is >apple<', '>', '<') == 'apple'
between_markers('No[/b] hi', '[b]', '[/b]') == 'No'
二、解题示例
1. 简单直观
def between_markers(text: str, begin: str, end: str) -> str:
"""
returns substring between two given markers
"""
# your code here
start_index = 0 if text.find(begin) == -1 else text.find(begin)
len_begin = 0 if text.find(begin) == -1 else len(begin)
end_index = text.find(end)
if end_index == -1:
return text[start_index++ len_begin:]
else:
return text[start_index + len_begin:end_index]
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'
print(between_markers('No [b]hi', '[b]', '[/b]'))
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!')
2
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]