Python - 字符串替换

时间:2015-10-24 18:09:54

标签: python string

我在做Google的Python课程: https://developers.google.com/edu/python/strings

练习链接: https://developers.google.com/edu/python/google-python-exercises.zip

练习: ./google-python-exercises/basic/strings2.py

在以下考试中:

echo "Enter numbers until -last- "
while read line
do
     array=("${array[@]}" $line)  
     if [ "$array[-1]" != "last" ]
     then
     break
     fi
done
 ......
 .....
 echo "average numbers of this blablabla " #this part is correct 

我的回答是:

# 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

我相信'晚餐很好'=='晚餐很好',但我不确定为什么我没有“OK”状态,而是“X”。我相信我没有正确的考试,但输出仍然是正确的。我是Python的新手,所以对此的评论将非常感激!

2 个答案:

答案 0 :(得分:3)

您错过了预期答案中的感叹号!。纠正解决方案的一种方法是使用查找bad的结果指定并合并替换子字符串的结束索引。

答案 1 :(得分:1)

我设法解决了这个问题:

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"