-3

I have a string and I want to split it based on word match. How can I do that? Here is my incomplete attempt

text_ = "Sky is beautiful today" 
test = "beautiful"

if test in text_:
    #Here the logic
    print(text_.split(test))

The above mentioned code does not work, becasue it removes the matched word

Expected output : ["Sky is","beautiful", "today"]

itsMe
  • 747
  • 1
  • 7
  • 23

3 Answers3

2

Regular expression operations are your friend!

A better way is to use re.split. This way you only need 1 line.

Note that the pattern (test) must be a string inside a parenthesis in order to include the word in the output.

text_ = "Sky is beautiful today" 
test = "(beautiful)"

print(re.split(test, text_))

Output: ['Sky is ', 'beautiful', ' today']

Carl Kristensen
  • 451
  • 3
  • 14
1

Well here is an approach I tried, quite a naive one but, works nonetheless for the above case.

text_ = "Sky is beautiful today" 
test = "beautiful"
s = ""
res = []
if test in text_:
  for word in text_.split(" "):
    if word == test:
      res.append(s)
      res.append(test)
      s = ""
    else:
      s += word + " "
  res.append(s)
print(res)

There will probably be more efficient methods too for sure.

The output :-

['Sky is ', 'beautiful', 'today ']
1

You could do something like this and make use of list slicing

Code

text = "Sky is beautiful today" 
element = "beautiful"

#Split string into list elements by the occurrence of a " "
words = text.split(" ")
index = words.index(element) #Grab index of specified "word"

preElement = " ".join(words[:index])      #Grab elements before the "word"
postElement = " ".join(words[index+1:])   #Grab elements after the "word"

#Combination, but only works for first occurrence of the "word"
output = [preElement,element,postElement]
print(output)

Output

['Sky is', 'beautiful', 'today']
Luc
  • 174
  • 10
  • No problem, but it would need some adjustments to work with multiple occurrences of the word you're looking for – Luc Jul 26 '20 at 09:51