2014-02-11 85 views
-1

请解释Python如何评估这个字符串,以便可以设置一个字的值大于字符串中的另一个字的值?如何b> n。Python字符串和排序?

def not_bad(s): 
    n = s.find('not') 
    b = s.find('bad') 
    if n != -1 and b != -1 and b > n: 
     s = s[:n] + 'good' + s[b+3:] 
    return s 
+0

发现返回的位置,那么你真的比较数字。 http://docs.python.org/2/library/string.html#string.find – sachleen

+0

请参阅[这个问题](http://stackoverflow.com/questions/4806911/string-comparison-technique-used-by- python) – eebbesen

+0

尝试用_'调用你的函数当乐队演奏lambada'_时,萨克斯演奏者弹出错误音符。 – pillmuncher

回答

1

bn整数str.find() method返回找到参数的str中的位置,如果未找到参数,则返回-1

因此,含有notbad任何字符串sbad如下not会做:

>>> s = "That's not bad at all" 
>>> n = s.find('not') 
>>> b = s.find('bad') 
>>> n 
7 
>>> b 
11 
>>> b > n 
True 
>>> s[:n] + 'good' + s[b+3:] 
"That's good at all" 
+0

谢谢 - 我明白 - 这对于在口译员中测试权利的练习非常有帮助。感谢你的帮助 – scopa