我是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(' ')
放入列表中,然后对各种元素进行排序,但我认为这可能只是为我自己创造了额外的工作。这节课还没有涉及到RegEx,所以解决方案不涉及RegEx。
这是我尝试的,但它并不是在所有情况下都能正确输出:
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
这是输出,它在1/4的测试用例中工作:
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")
UPDATE:这段代码解决了这个问题:
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
感谢大家帮助我找到解决方案(而不仅仅是给我答案)!我很感激!
嗯,我想是时候做一个小小的回顾了;-)
你的代码中有一个错误: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
这样分解:
- 您如何确定单词"not"是否在字符串中?
- 如果单词"not"在字符串中,您如何找出 ?
- 你如何在一次操作中结合#1和#2 ?
- 和#1-3一样,除了"坏"这个词?
- 如果你知道单词"not"one_answers"bad"都在一个字符串中,你如何确定单词"bad"是否出现在单词"not"之后?
- 如果你知道"bad"在"not"之后,你如何得到单词"not"之前的字符串的每一部分?
- 你怎么得到单词"bad"后面的字符串的每一部分?
- 你会如何将#6和#7的答案结合起来,以取代从单词"not"开头到单词"bad"末尾的所有内容?
既然你正在尝试学习,我不想把答案交给你,但我将首先在python文档中查找一些字符串函数,包括replace和index。
此外,如果您有一个好的IDE,它可以通过显示附加到对象的方法甚至自动显示这些方法的帮助字符串来帮助您。我倾向于在大型项目中使用Eclipse,而在小型项目中使用轻量级的Spyder
http://docs.python.org/library/stdtypes.html#string-methods
我怀疑他们想让你使用string。查找以定位各种子字符串:
>>> mystr = "abcd"
>>> mystr.find("bc")
1
>>> mystr.find("bce")
-1
既然你试图自学(好吧,顺便说一句:)我不会发布一个完整的解决方案,但也要注意,你可以使用索引来获取子字符串:
>>> mystr[0:mystr.find("bc")]
'a'
希望这足以让你开始!如果没有,请在这里评论,我可以发布更多。:)
def not_bad(s):
snot = s.find("not")
sbad = s.find("bad")
if snot < sbad:
s = s.replace(s[snot:(sbad+3)], "good")
return s
else:
return s