-1

当字符串与索引匹配时 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()
4

1 回答 1

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")
于 2013-10-10T12:14:56.037 回答