无法在最后一行执行if的else部分

时间:2013-10-10 11:55:04

标签: python

当字符串与索引匹配时,如果if语句代码中的else块没有按预期工作。 但是当添加其他部分时,它总是显示"没有字符串"

import sys


def string_search_index():
    '''
    This function search a string in a file through index and gives the result.    

    '''
    if len(sys.argv) != 3:
        print "Enter Two Arguments Only"
        sys.exit(1)

    stringsrch = sys.argv[2]
    #size = len(sys.argv)
    file_name = open("passwd", "r")
    #print "No of Argu ", size

    if sys.argv[1].isdigit():
        fieldindex = int(sys.argv[1])-1
    else:
        print "Enter Integer in 1st Argument"
        sys.exit(1)
    fieldindex = int(sys.argv[1])-1

    for store_file in file_name:
        temp = store_file.split(":")
        search = temp[fieldindex]
        #print search 

        if stringsrch in search:
            print store_file
        else:
            print "No String"
            sys.exit(1)


string_search_index()

1 个答案:

答案 0 :(得分:1)

string not found测试应该在for循环之外:

file = open("my_file", "r")
string_found = False
# Loop over the lines of the file
for line in file:
    temp = line.split(":")
    if test_string in temp[index]:
        print('Found it : {}'.format(line))
        string_found = True
# String not found case
if not string_found:
    print("String not found")