找到字符串后如何从字符串中检索字符?

我想搜索字符串中的一些字符,然后将它们保存在变量中,但以字符串中的写入方式保存。例如:


text = "this is a Long text"

searchinput = "a long"


if searchinput.lower() in text.lower():

    print(searchinput)

输出当然是“a long”,但我希望输出与文本变量中的输出完全相同,即“a Long”。


简而言之:检查字符串是否在较长字符串中,然后检索长字符串版本。我怎样才能做到这一点?


慕田峪9158850
浏览 115回答 2
2回答

烙印99

您可以尝试获取索引,然后从那里开始。这是一个给你一个想法的例子。text = "this is a Long text"check = "a long"try:    i = text.lower().index(check.lower())    print(text[i:i+len(check)])except:    print('Not Found')

眼眸繁星

您可以使用正则表达式。Python 示例:import reregex = r"a long"test_str = "this is a Long text"regexMatches = re.finditer(regex, test_str, re.IGNORECASE)matches = [i.group() for i in regexMatches]print(matches)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python