Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Split a string by a word which contains a substring

I have a string text = "Fix me a meeting in 2 days". I have a list of some words meetingStrings. "meet" is there in meetingStrings. So, I have to split the text by meeting.

Desired Output :

in 2 days

meetingStrings = [
    "appointment",
    "meet",
    "interview"
]
text = "Fix me a meeting in 2 days"
for x in meetingStrings:
    if x in text.lower(): 
        txt = text.split(x, 1)[1]
        print(txt)

This gives Output:

ing in 2 days.

like image 870
Anurag Avatar asked Nov 27 '25 18:11

Anurag


2 Answers

Using re.split():

import re

meetingStrings = [
    "appointment",
    "meet",
    "interview"
]

text = "Fix me a meeting in 2 days"

print(re.split('|'.join(r'(?:\b\w*'+re.escape(w)+r'\w*\b)' for w in meetingStrings), text, 1)[-1])

Prints:

 in 2 days
like image 154
Andrej Kesely Avatar answered Nov 29 '25 06:11

Andrej Kesely


With a small change to your code:

meetingStrings = [
    "appointment",
    "meet",
    "interview"
]
text = "Fix me a meeting in 2 days"
for x in meetingStrings:
    if x in text.lower():
        txt = text.split(x, 1)[1]
        print(txt.split(" ", 1)[1]) #<--- Here

Just take your final output, and split at the first occurrence of a space

like image 23
neko Avatar answered Nov 29 '25 06:11

neko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!