Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/310.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
截断Python中字符串中的单词周围的字符串_Python_Find_Slice - Fatal编程技术网

截断Python中字符串中的单词周围的字符串

截断Python中字符串中的单词周围的字符串,python,find,slice,Python,Find,Slice,我想在字符串中找到一个单词,然后截断该单词周围的python字符串 例如: str1=“我想尝试并选择这个世界上的某些特定事物。你能帮我做吗” 现在我想在字符串中找到特定的单词,然后从前面和结尾截断字符串,在该单词周围留出15个字符 所以答案是这样的: “nd选择此中的某些特定内容” 这基本上是15个字符左右的“具体” 提前感谢使用find()函数如何,该函数返回要搜索的单词的第一个字母的索引,否则会引发异常: x = "I want to try and select some sp

我想在字符串中找到一个单词,然后截断该单词周围的python字符串

例如: str1=“我想尝试并选择这个世界上的某些特定事物。你能帮我做吗”

现在我想在字符串中找到特定的单词,然后从前面和结尾截断字符串,在该单词周围留出15个字符

所以答案是这样的: “nd选择此中的某些特定内容”

这基本上是15个字符左右的“具体”


提前感谢

使用
find()
函数如何,该函数返回要搜索的单词的第一个字母的索引,否则会引发异常:

x = "I want to try and select some specific thing in this world. Can you please help me do that"
word = "specific"
limit = 15

try:
    index = x.find(word)
    output = x[max(0, index-limit):min(len(x), index+limit+len(word))]
    print(output)
except:
    print("Word not found")
哦,
x[:]
是一种拼接字符串的方法,这是python调用子字符串的方法

max和min函数防止子字符串的限制超出原始输入的长度