Search code examples
pythonlistindices

Manually keying in a number for list indices in python


I have a list of file name eg. filenames=['blacklisted.txt', 'abc.txt', 'asfafa.txt', 'heythere.txt']

I would like to allow the users to manually choose which file name to display , for example ,

*

print "Please key in the first log file you would like to use: "
choice1=raw_input()
print"Please key in the second log file you would like to use: "
choice2=raw_input()
filename1=filenames[choice1]
filename2=filenames[choice2]
print filename1
print filename2

*

However, i got the error : filename1=filenames[choice1] TypeError: list indices must be integers, not str.

Any advice ? Thanks!


Solution

  • You have to first convert the input to int using int()

    print "Please key in the first log file you would like to use: "
    choice1=raw_input()
    .
    .
    filename1=filenames[int(choice1)]
    .
    

    or you could convert the input straight to int

    choice1 = int(raw_input())
    filename1 = filenames[choice1]
    

    You should also display the list of files with their corresponding index numbers so the user would know which to choose.

    UPDATE

    For error handling, you can try something like

    while True:
        choice1 = raw_input('Enter first file name index: ')
        if choice1.strip() != '':
            index1 = int(choice1)
            if index1 >= 0 and index1 < len(filenames):
                filename1 = filenames[index1]
                break // this breaks the while loop when index is correct
    

    and the same for choice2