如果条件,则忽略某些单词

时间:2016-01-04 19:49:39

标签: python if-statement

如果除了"忽略关键字"以外的任何其他内容,如何在字符串上创建if条件其次是" foo-" 例如:以下两个字符串应分别通过和失败:

  

success =' \ nrandom stuff,foo-忽略关键字\ nfoo +忽略   关键字\ n随机的东西; \ nfoo-忽略关键字'

     

fail =' \ nrandom stuff,foo-忽略关键字\ nfoo +忽略   关键字\ n随机的东西; \ nfoo-忽略关键字\ nfoo-这个   应该失败'

我正在尝试这条线并且无法使其发挥作用:

Project -> Clean...

1 个答案:

答案 0 :(得分:0)

现在它完全符合您的要求:

success = '\nrandom stuff,foo- Ignore keyword\nfoo+ Ignore keyword\n random stuff;\nfoo- Ignore keyword'

fail = '\nrandom stuff,foo- Ignore keyword\nfoo+ Ignore keyword\n random stuff;\nfoo- Ignore keyword\nfoo- this should fail'
# to be successful only "Ignore keyword" after "foo- "
elem_to_search = "foo- "
keyword = "Ignore keyword"

def check_sentence(elem_to_search, keyword, string_to_check):
    index = 0
    keyword_first = len(elem_to_search)
    keyword_last = len(elem_to_search) + len(keyword)

    while index < len(string_to_check):
        index = string_to_check.find(elem_to_search, index)
        if index == -1:
            break
        elif string_to_check[index + keyword_first : index + keyword_last] == keyword:
            index += len(elem_to_search)
        else:
            print "fail"
            break

check_sentence(“foo-”,“忽略关键字”,成功)将通过

check_sentence(“foo-”,“忽略关键字”,失败)将打印失败。