繁体   English   中英

删除python中字符串中2个匹配词之间的词

[英]Deletion of words between 2 matching words in a string in python

假设有一个字符串

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

假设n="India "

然后我想要结果

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

所以我的意思是从一个字符串中我想删除\直到一个重复第二次的特定单词之间的所有句子。 希望,我的问题很清楚。 我无法用更好的方式解释它

另一种方法是使用内置的str.count()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)

使用x.find和起点像这样尝试

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'

使用重新

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'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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