Python字符串替换
我在上谷歌的Python课程: 链接到练习: 练习: ./googlepython练习/basic/strings2.py 在以下考试中:Python字符串替换,python,string,Python,String,我在上谷歌的Python课程: 链接到练习: 练习: ./googlepython练习/basic/strings2.py 在以下考试中: # 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 'g
# 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
我的回答是:
def not_bad(s):
not_position = s.find('not')
bad_position = s.find('bad')
if bad_position > not_position:
s = s.replace(s[not_position:],'good')
return s
当我运行检查器时,我得到以下信息:
not_bad
OK got: 'This movie is good' expected: 'This movie is good'
X got: 'This dinner is good' expected: 'This dinner is good!'
OK got: 'This tea is not hot' expected: 'This tea is not hot'
OK got: "It's bad yet not" expected: "It's bad yet not"
我相信“这顿饭很好”==“这顿饭很好”,但我不确定为什么我没有得到“OK”状态,而是“X”。我相信我没有正确的考试,但输出仍然是正确的。我是Python新手,因此对此发表评论将不胜感激 你错过了感叹号
代码>在预期答案中。纠正解决方案的一种方法是使用查找bad
的结果指定并合并替换子字符串的结束索引 你错过了感叹号代码>在预期答案中。纠正解决方案的一种方法是使用查找bad
的结果指定并合并替换子字符串的结束索引 我已经设法解决了这个问题:
def not_bad(s):
not_position = s.find('not')
bad_position = s.find('bad')
if bad_position > not_position:
s = s.replace(s[not_position:bad_position+3],'good')
return s
not_bad
OK got: 'This movie is good' expected: 'This movie is good'
OK got: 'This dinner is good!' expected: 'This dinner is good!'
OK got: 'This tea is not hot' expected: 'This tea is not hot'
OK got: "It's bad yet not" expected: "It's bad yet not"
我设法解决了这个问题:
def not_bad(s):
not_position = s.find('not')
bad_position = s.find('bad')
if bad_position > not_position:
s = s.replace(s[not_position:bad_position+3],'good')
return s
not_bad
OK got: 'This movie is good' expected: 'This movie is good'
OK got: 'This dinner is good!' expected: 'This dinner is good!'
OK got: 'This tea is not hot' expected: 'This tea is not hot'
OK got: "It's bad yet not" expected: "It's bad yet not"
很好!=好!代码>。注意代码>很好的观点,我将尝试修复它很好!=好!代码>。注意代码>很好的一点,我将尝试修复它