简体   繁体   中英

python … how to get specific item from a string and item before it [on hold]

function and I provide for ex the word ( play ) and It ask for item before it and after it

and just say If the occurrence of the word play 5 times in the string

so it will return to me 5 sentences containing play

Example

part of the string say

andry and I love playing football and play piano with Jack and Paul...

output :

I love ... Jack 

so the function should be like this:

sentence(before_the_exact_word, the_exact_word, after_the_exact_word)
sentence("I", "play", "jack")

The question is not very clear, as stated in the comments, but see if this is what you are looking for:

sentence = 'andry and I love playing football and play piano with Jack and Paul...'
before, the_exact_word, after = "I", "play", "Jack"
words = sentence.split()
new_sentence = []
for i in range(len(words)):
    if len(new_sentence) > 0 or words[i] == before:
        new_sentence.append(words[i])
        if words[i] == after:
            break
new_sentence = ' '.join(new_sentence) if the_exact_word in new_sentence else []
new_sentence # OUTPUT 'I love playing football and play piano with Jack'

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