python-checkio/Elementary/between-markers.py
2019-12-24 14:52:17 +01:00

28 lines
1.1 KiB
Python

import re
def between_markers(text: str, begin: str, end: str) -> str:
"""
returns substring between two given markers
"""
if text.count(begin) == 0:
text = begin+text
if text.count(end) == 0:
text = text+end
found = re.findall(r"{}(.*){}".format(re.escape(begin), re.escape(end)), text)
return found[0] if len(found) > 0 else ""
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!')