简体   繁体   中英

Truncate a string around a word found in that string in Python

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM