CheckiO 是面向初学者和高级程序员的编码游戏,使用 Python 和 JavaScript 解决棘手的挑战和有趣的任务,从而提高你的编码技能,传送门:https://checkio.org/,本博客主要记录自己在闯关时的做题思路和实现代码,同时也学习学习其他大神写的代码。
题目描述
【Between Markers】:给定一个字符串和两个标记字符(第一个和最后一个标记),找到两个标记符之间包含的子字符串。初始标记和最终标记始终不同;如果这两个标记在字符串中都不存在,则返回原字符串;如果没有初始标记,则应将第一个字符视为字符串的开头;如果没有最终标记,则最后一个字符应视为字符串的结尾;如果最终标记位于初始标记之前,则返回一个空字符串。
【链接】:https://py.checkio.org/zh-hans/mission/between-markers/
【输入】:三个参数,都是字符串,第二个和第三个参数是初始标记和结束标记
【输出】:字符串
【范例】:
between_markers('What is >apple<', '>', '<') == 'apple'
between_markers('No[/b] hi', '[b]', '[/b]') == 'No'
解题思路
利用 find()
方法查找原字符串中是否有标记字符,注意,由于 find()
方法会返回字符串出现的索引位置,而要提取标记字符之间的字符串,初始标记的位置就要加上他的长度,具体分四种情况:
有初始标记、有结束标记:利用切片,返回初始标记和结束标记之间的字符串;
无初始标记、无结束标记:返回原字符串;
有初始标记、无结束标记:利用切片,返回初始位置到字符串最后位置的字符串;
无初始标记、有结束标记:初始位置置零,利用切片,返回初始位置到结束标记之间的字符串
代码实现
def between_markers(text: str, begin: str, end: str) -> str:
"""
returns substring between two given markers
"""
start = text.find(begin)
finish = text.find(end)
if start != -1 and finish != -1:
start += len(begin)
return text[start:finish]
elif start == -1 and finish == -1:
return text
elif start != -1 and finish == -1:
start += len(begin)
return text[start:]
elif start == -1 and finish != -1:
start = 0
return text[start:finish]
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!')
大神解答
大神解答 NO.1
import re
def between_markers(text: str, begin: str, end: str) -> str:
"""
returns substring between two given markers
"""
try:
start = text.index(begin) + len(begin)
except ValueError:
start = 0
try:
finish = text.index(end)
except ValueError:
finish = len(text)
return text[start:finish]
index()
方法检测字符串中是否包含子字符串,如果指定了开始和结束范围,则检查是否包含在指定范围内,该方法与 find()
方法一样,只不过如果子字符串不在原字符串中会报一个异常。
大神解答 NO.2
def between_markers(text: str, begin: str, end: str) -> str:
"""
returns substring between two given markers
"""
return text[(lambda x,y: 0 if x == -1 else x + y)(text.find(begin), len(begin)):
(lambda x,y: y if x == -1 else x)(text.find(end), len(text))]
大神解答 NO.3
def between_markers(text: str, first_mark: str, second_mark: str) -> str:
"""
returns substring between two given markers
"""
begin = text.find(first_mark)
end = text.find(second_mark)
if begin < 0:
begin = 0
else:
begin += len(first_mark)
if end < 0:
end = len(text)
if end < begin:
return ''
return text[begin: end]
来源:CSDN
作者:TRHX
链接:https://blog.csdn.net/qq_36759224/article/details/103483228