我想在字符串中找到一个单词,然后截断该单词周围的 python 字符串。示例:str1 =“我想尝试选择这个世界上的一些特定事物。你能帮我做到这一点吗”现在我想找到字符串中特定的单词,然后从头到尾截断字符串以表示该单词周围的 15 个字符。所以答案是这样的:“并在其中选择一些特定的东西”这基本上是“具体”左右 15 个字符。提前致谢
1 回答
![?](http://img1.sycdn.imooc.com/54dc06a60001ef0401000100-100-100.jpg)
qq_花开花谢_0
TA贡献1835条经验 获得超7个赞
怎么样使用该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 函数可防止子字符串的限制超出原始输入的长度
添加回答
举报
0/150
提交
取消