Python 删除索引之间字符串的一部分

Python 删除索引之间字符串的一部分,python,string,python-2.7,replace,indices,Python,String,Python 2.7,Replace,Indices,我要写一个函数,当给定一个字符串时,它会找到 子字符串“not”和“bad”。如果'bad'跟在'not'后面,它将整个'not'…'bad'子字符串替换为'good'。 例:“这顿饭没那么糟!”这顿饭很好! 我试过: def不坏: sub1='not' sub2='坏' 如果s.find(sub1)

我要写一个函数,当给定一个字符串时,它会找到 子字符串“not”和“bad”。如果'bad'跟在'not'后面,它将整个'not'…'bad'子字符串替换为'good'。 例:“这顿饭没那么糟!”这顿饭很好! 我试过:

def不坏:
sub1='not'
sub2='坏'
如果s.find(sub1)

但是它不会在结尾产生感叹号。

您可以在这里使用
re

import re
s='This dinner is not that bad!'
re.sub(r'not \w+ bad','good',s)
# 'This dinner is good!'

\w+
-匹配任何单词字符(等于
[a-zA-Z0-9\

我没有使用正则表达式,因为我真的不知道如何使用。但我的解决方案是:

def not_bad(s):
    sub1='not'
    sub2='bad'
    temp = None
    if s[len(s)-1] == "!": #-> this checks if there is "!"
        temp = s[len(s)-1]
    if s.find(sub1) or s.find(sub2):
        s = s[:int(s.find(sub1))]
        s += 'good'
        if temp:
            s += temp
        return s
    else:
        return s

@ch3ster是正确的,但这只能解释一个词。对于更多的字符,您应该尝试以下操作

import re

string1="the dinner is not nice 27 that bad"
print(re.sub(r"not[a-zA-Z _0-9]*bad","good",string1))
输出

the dinner is good
请检查这个

def not_bad(main_str):
    sub1='not'
    sub2='bad'
    if main_str.find(sub1) < main_str.find(sub2):
        main_str = main_str[0:int(main_str.find(sub1))] + 'good' + main_str[int(main_str.find(sub2)) + len(sub2):]
        return main_str
    else:
        return main_str


output_str = not_bad('This dinner is not that bad!')
print(output_str)

关于
s.replace('not that bad','good')呢?
该函数应该适用于任何给定的字符串。因此,如果给定的字符串是“茶没有那么热”,那么它将不起作用
不是因为字符串中总是存在
?你怎么找到反义词呢?你需要一些图书馆。或者存储单词的反义词。为什么要使用Python 2?另外,你的代码缩进被破坏了。这是一个练习的一部分,有一个单独的代码通过应用参数来检查我的代码。此外,如果我的缩进被破坏,代码将根本不起作用,但它确实起作用。您可以编写
”和“
”而不是
”或“
”,这两种代码对我都有效。。但是做你的测试:)希望如此。我帮助EDI有没有办法让函数替换not和bad之间的索引,而不管感叹号是什么?我的代码检查是否有感叹号,只是为了知道是否要把它放在最后。您可以删除检查是否有感叹号的
'if'
。如果您只想更改单词“not”,您可以这样做:
打印(s[s.find(sub1):s.find(sub1)+len(sub1)]
这将捕获单词“not”的起始索引,并从起始索引运行到起始索引+单词“not”的长度。如果您打印它,它将打印“不是”。:)请注意,这不是最好的方法,更好的方法是将
s.find(sub1)
的返回值保存在变量中
def not_bad(main_str):
    sub1='not'
    sub2='bad'
    if main_str.find(sub1) < main_str.find(sub2):
        main_str = main_str[0:int(main_str.find(sub1))] + 'good' + main_str[int(main_str.find(sub2)) + len(sub2):]
        return main_str
    else:
        return main_str


output_str = not_bad('This dinner is not that bad!')
print(output_str)
This dinner is good!