我想在字符串中找到一個單詞,然后截斷該單詞周圍的 python 字符串。示例:str1 =“我想嘗試選擇這個世界上的一些特定事物。你能幫我做到這一點嗎”現在我想找到字符串中特定的單詞,然后從頭到尾截斷字符串以表示該單詞周圍的 15 個字符。所以答案是這樣的:“并在其中選擇一些特定的東西”這基本上是“具體”左右 15 個字符。提前致謝
1 回答

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
提交
取消