识别子字符串并根据顺序返回响应的Python方法
我刚开始学习Python,正在通过谷歌代码大学的在线课程自学。课程中有一个关于字符串处理的练习,内容如下:
# E. not_bad
# Given a string, find the first appearance of the
# substring 'not' and 'bad'. If the 'bad' follows
# the 'not', replace the whole 'not'...'bad' substring
# with 'good'.
# Return the resulting string.
# So 'This dinner is not that bad!' yields:
# This dinner is good!
def not_bad(s):
# +++your code here+++
return
我卡住了。我知道可以用 ls = s.split(' ')
把字符串分成一个列表,然后去掉一些元素再排序,但我觉得这样可能会给自己增加额外的工作量。课程还没有讲到正则表达式,所以解决方案不涉及re。谁能帮帮我?
这是我尝试过的代码,但在所有情况下输出结果都不太正确:
def not_bad(s):
if s.find('not') != -1:
notindex = s.find('not')
if s.find('bad') != -1:
badindex = s.find('bad') + 3
if notindex > badindex:
removetext = s[notindex:badindex]
ns = s.replace(removetext, 'good')
else:
ns = s
else:
ns = s
else:
ns = s
return ns
这是输出结果,在四分之一的测试案例中有效:
not_bad
X got: 'This movie is not so bad' expected: 'This movie is good'
X got: 'This dinner is not that bad!' expected: 'This dinner is good!'
OK got: 'This tea is not hot' expected: 'This tea is not hot'
X got: "goodIgoodtgood'goodsgood goodbgoodagooddgood goodygoodegoodtgood
goodngoodogoodtgood" expected: "It's bad yet not"
测试案例:
print 'not_bad'
test(not_bad('This movie is not so bad'), 'This movie is good')
test(not_bad('This dinner is not that bad!'), 'This dinner is good!')
test(not_bad('This tea is not hot'), 'This tea is not hot')
test(not_bad("It's bad yet not"), "It's bad yet not")
更新:这段代码解决了问题:
def not_bad(s):
notindex = s.find('not')
if notindex != -1:
if s.find('bad') != -1:
badindex = s.find('bad') + 3
if notindex < badindex:
removetext = s[notindex:badindex]
return s.replace(removetext, 'good')
return s
谢谢大家帮我找到了解决方案(而不是直接给我答案)!我很感激!
5 个回答
1
既然你在学习,我不想直接给你答案,但我建议你可以先去看看Python的文档,里面有一些关于字符串的函数,比如replace(替换)和index(索引)。
另外,如果你有一个好的开发环境(IDE),它可以帮助你查看一个对象有哪些方法,甚至会自动显示这些方法的帮助信息。我通常在大项目中使用Eclipse,而在小项目中则用轻量级的Spyder。
3
把问题分解成这样:
- 你怎么判断一个字符串里有没有“not”这个词?
- 如果有“not”,你怎么找出它在字符串中的位置?
- 你怎么把第1步和第2步结合起来,一次性完成?
- 第1到第3步同样适用于“bad”这个词吗?
- 假设你知道“not”和“bad”这两个词都在字符串里,你怎么判断“bad”是在“not”之后出现的?
- 假设你知道“bad”是在“not”之后,你怎么获取“not”之前的所有部分?
- 你怎么获取“bad”之后的所有部分?
- 你怎么把第6步和第7步的结果结合起来,把“not”这个词开始到“bad”这个词结束的部分替换成“good”?
3
好吧,我觉得是时候做个小总结了 ;-)
你的代码里有个错误:notindex > badindex
应该改成 notindex < badindex
。改了之后代码看起来就能正常工作了。
另外,我对你的代码还有一些建议:
- 通常的做法是先计算出一个值,然后把它赋给一个变量,接下来在下面的代码中使用这个变量。这个规则在你这个例子里是适用的:
比如,你可以把函数的开头改成:
notindex = s.find('not')
if notindex == -1:
- 你可以在函数里多次使用
return
。
这样一来,你的代码后面部分就能大大简化:
if (*all right*):
return s.replace(removetext, 'good')
return s
最后,我想提一下,你可以用 split
来解决这个问题。不过,这似乎不是更好的解决方案。
def not_bad( s ):
q = s.split( "bad" )
w = q[0].split( "not" )
if len(q) > 1 < len(w):
return w[0] + "good" + "bad".join(q[1:])
return s