简体   繁体   English

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

[英]How can I retrieve characters from a string after finding them?

I would like to search some characters in a string and then save them in a variable but the way it is written in the string.我想在字符串中搜索一些字符,然后将它们保存在一个变量中,但它是在字符串中写入的方式。 For example:例如:

text = "this is a Long text"
searchinput = "a long"

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

The output is, of course, "a long", but I want the output to be exactly as in the text variable, that is "a Long".输出当然是“a long”,但我希望输出与文本变量中的完全一样,即“a Long”。

In short: Check if a string is in a longer string and than retrieve the long string version.简而言之:检查字符串是否在更长的字符串中,然后检索长字符串版本。 How can I do that?我怎样才能做到这一点?

You could try to get the index and then go from there.您可以尝试获取索引,然后从那里开始。 This is an example to give you an idea.这是一个给你一个想法的例子。

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

You can use regex .您可以使用正则表达式

Python example:蟒蛇示例:

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 转换为字符串后如何从字典值中检索最后5个字符 - How to retrieve the last 5 characters from dictionary value after converting to string 如何从列表中隔离超出的字符并计算它们? - How can I isolate the exceeding characters from a list and count them? pandas dataframe Python 中如何从字符串中提取出某些字符,转换成相应的数字形式用于计算? - How can I extract certain characters from a string, convert them to corresponding numeric form and use for calculation in pandas dataframe in Python? 如何使用正则表达式查找字符串中是否包含2个特定字符,如果存在则将其删除? - How can I use regex to find if a string has 2 specific characters and remove them if they are? 如何删除数据集所有行的字符串中 x 个字符后的所有字符? - How can I remove all characters after x number of characters in a string for all rows of a data set? 在wxpython中动态创建文本控件。 我如何从中检索数据? - Created text controls dynamically in wxpython. How can i retrieve the data from them? 如何一次从 Python 字符串中提取三个字符? - How can I extract three characters at a time from a Python string? 如何从字符串中间获取2个字符? - How can I get 2 characters from the middle of a string? 如何从字符串中删除前 2 个字符 - python - How can I strip the first 2 characters from a string - python 我如何使用正则表达式从字符串中删除重复的字符 - How I can use regex to remove repeated characters from string
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM