Reputation: 113
I want to find a word in a string and then truncate the python string around that word.
Example: str1 = "I want to try and select some specific thing in this world. Can you please help me do that"
Now I want to find the word specific in the string and then truncate the string from front and end to say 15 chars around that word.
So the answer would be something like: "nd select some specific thing in this "
This is basically 15 characters left and right from "specific".
Thanks in advance
Upvotes: 0
Views: 711
Reputation: 3553
How about using the find()
function, which returns the index of the first letter of the word to be searched, otherwise raises an exception:
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")
Oh and the x[:]
is a method to splice the string, which is the python way to call a substring
The max and min functions prevent the substring's limits from going beyond the length of the original input
Upvotes: 1