我不确定为什么在测试此功能时我会多次重复此行。有人可以帮我解决这个问题吗?我希望在标题之前返回一个字符串,然后删除所有内容。
"</head>hello python world </head> , i'm a beginner</head>hello python
world </head> , i'm a beginner</head>hello python world </head> "
def get_header(s):
'''(str) -> str
Return the start of the given string up to and including
</head>.
>>> get_header("hello python world </head> , i'm a beginner ")
'hello python world </head>'
'''
new_s = ''
tag = '</head>'
for item in s:
new_s = new_s + tag + s.strip()
return new_s
答案 0 :(得分:0)
您可以使用正则表达式:
import re
def get_header(s):
return re.findall('[\w\s]+\</head\>', s)[0]
print(get_header("hello python world </head> , i'm a beginner "))
输出:
hello python world </head>
修改:不含re
:
def get_header(s):
return s[:s.index('</head>')+7]
如果没有硬编码,您也应该将头部值传递给函数:
def get_header(s, key):
return s[:s.index(key)+len(key)]