Python 从字符串中提取子字符串和x个字符

Python 从字符串中提取子字符串和x个字符,python,string,Python,String,我有一个字符串: desc = 'Communication is a cornerstone of society. It is the expression of people who want to feel connected and share their thoughts, interests and feelings with one another. And telecommunication allows us to interact even when we are in d

我有一个字符串:

desc = 'Communication is a cornerstone of society. It is the expression of people who want to feel connected and share their thoughts, interests and feelings with one another. And telecommunication allows us to interact even when we are in different places and separated by a distance.'
如果一个特定的子字符串在desc中,我想提取该子字符串以及它后面的下一个x字符

例:


我不知道如何获取特定子字符串后的x字符。

您可以这样做,您可以使用索引切片

string = 'Communication is a cornerstone of society'

substring = 'Communication'

x = 15

if substring in string:
    index = string.find(substring)
    print(string[index:index + x])
可以使用index()或find()获取子字符串的起始位置,然后切片以获取所需的字符

def get_sub_x(full, sub, x):
   try:
      index = full.index(sub)
      return full[index: index + len(sub) + x]
   except ValueError:
      return None

print(get_sub_x('Hello World', 'Wo', 2))
输出
Worl

试试这个

n=15
关键词=“社会”
found=re.search(f“({keyword}.*)”,desc.group(0)
found=found[len(关键字)+n]
打印(已找到)
#"社会,。它表达的是那些希望彼此联系并分享想法、兴趣和感受的人。而且,即使我们身处不同的地方,相隔很远,电信也能让我们进行互动。”

OP说他想要子字符串+下一个X字符。只需在切片中添加原始子字符串的长度。此解决方案将始终获取从特定子字符串到结尾的文本,这不是我想要的。你可以将找到的文本作为子字符串。你想如何选择下一个x字符?我的意思是,你需要为你的子字符串设置一个正则表达式,例如,在第一种情况下,在远程通信和交互之间的子字符串,或者你想随时手动设置x?
def get_sub_x(full, sub, x):
   try:
      index = full.index(sub)
      return full[index: index + len(sub) + x]
   except ValueError:
      return None

print(get_sub_x('Hello World', 'Wo', 2))
def get_index (string):
    if string in desc:
        return desc.index (string)

start = get_index ('telecommunications ')
end = get_index ('even')
print (desc [start:end])