Home > Blockchain >  Deletion of words between 2 matching words in a string in python
Deletion of words between 2 matching words in a string in python

Time:10-03

Suppose there is a string

x="India is the country of festivals. India is known for its rich culture. National bird of India is peacock"

and suppose n="India"

then I want result as

x="India is known for its rich culture. National bird of India is peacock"

So what I mean is from a string I want to delete all sentences between\till a particular word which is repeated 2nd time. Hope, my question is clear. I couldn't explain it in a better way

CodePudding user response:

Try it like this using x.find and a starting point

x = "India is the country of festivals. India is known for its rich culture. National bird of India is peacock"
n = "India"
first = x.find(n, 0)
second = x.find(n, first 1)
print(x[0:first]   x[second:len(x)])  # 'India is known for its rich culture. National bird of India is peacock'

CodePudding user response:

Another way, use built-in str.count() and str.split().

x = 'India is the country of festivals. India is known for its rich culture. National bird of India is peacock'
n = 'India'
if x.split().count(n) >= 2: # be sure to count at **word** level
    pre, mid, post = x.split(n, 2)
    print(pre   n   post)
else:
    print(x)

CodePudding user response:

Using re

import re
x="India is the country of festivals. India is known for its rich culture. National bird of India is peacock"
n = 'India'
lst = [m.start() for m in re.finditer(n, x)]

x[:lst[0]]   x[lst[1]:]

# 'India is known for its rich culture. National bird of India is peacock'
  • Related