ELEMENTARY.05.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<, >, <) == applenbetween_markers(No[/b] hi, [b], [/b]) == Non
我的代碼:
def between_markers(text: str, begin: str, end: str) -> str:n l1 = []n if begin not in text and end not in text:n return textn elif begin in text and end in text:n l1 = text[text.index(begin)+len(begin):text.index(end)]n return l1n elif begin not in text and end in text:n l1 = text[0:text.index(end)]n return l1n elif begin in text and end not in text:n l1 = text[text.index(begin)+len(begin):]n return l1n elif text.index(begin) > text.index(end):n return n
高人們的:
第一個,Clear:
def between_markers(text: str, begin: str, end: str) -> str:n start = text.find(begin) + len(begin) if begin in text else Nonen stop = text.find(end) if end in text else Nonen return text[start:stop]n
第二個,Creative:
def between_markers(txt, begin, end):n a, b, c = txt.find(begin), txt.find(end), len(begin)n return [txt[a+c:b], txt[a+c:], txt[:b], txt][2*(a<0)+(b<0)]n
第三個,Speedy:
def between_markers(text: str, begin: str, end: str) -> str:n begin_index = text.find(begin) if begin in text else -1n end_index = text.find(end) if end in text else len(text)n add_index = len(begin) if begin_index != -1 else 1n return text[begin_index+add_index:end_index] if begin_index < end_index else n
推薦閱讀:
※python裝飾器的問題?
※編程零基礎,如何學習Python?
※本人精通c++ ,請問自學python哪本書好一點?
※python適合做數據分析還是做開發?
※學習python有什麼用?python的實際應用有哪些?