2014-02-11 191 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