Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
index, then if-elif solution in Clear category for Between Markers by hbczmxy
def between_markers(text: str, begin: str, end: str) -> str:
"""
returns substring between two given markers
"""
# find the index of the left limiting marker (if there is one)
# then find the index of the right limiting marker (if there is one)
begin_index , end_index = text.find(begin), text.find(end)
begin_index = begin_index + len(begin) if begin_index != -1 else -1
end_index = end_index if end_index != -1 else -1
# the two marker are all in the string (and they are in right direction)
if begin_index < end_index and begin_index != -1 and end_index != -1:
return text[begin_index:end_index]
# Wrong direction
elif begin_index > end_index and begin_index != -1 and end_index != -1:
return ''
# No opened
elif begin_index == -1 and end_index != -1:
return text[:end_index]
# No close
elif end_index == -1 and begin_index != -1:
return text[begin_index:]
# No markers at all
elif begin_index == -1 and end_index == -1:
return text
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("My new site",
"", "") == "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 ', '>', '<') == '', 'Wrong direction'
print('Wow, you are doing pretty good. Time to check it!')
Sept. 7, 2021
Comments: