为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕田峪9158850 2023-09-05 15:14:29
我想搜索字符串中的一些字符,然后将它们保存在变量中,但以字符串中的写入方式保存。例如:text = "this is a Long text"searchinput = "a long"if searchinput.lower() in text.lower():    print(searchinput)输出当然是“a long”,但我希望输出与文本变量中的输出完全相同,即“a Long”。简而言之:检查字符串是否在较长字符串中,然后检索长字符串版本。我怎样才能做到这一点?
查看完整描述

2 回答

?
烙印99

TA贡献1829条经验 获得超13个赞

您可以尝试获取索引,然后从那里开始。这是一个给你一个想法的例子。


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')


查看完整回答
反对 回复 2023-09-05
?
眼眸繁星

TA贡献1873条经验 获得超9个赞

您可以使用正则表达式

Python 示例:

import re

regex = 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)


查看完整回答
反对 回复 2023-09-05
  • 2 回答
  • 0 关注
  • 85 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信