Manually keying in a number for list indices in python -


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

i allow users manually choose file name display , example ,

*

print "please key in first log file use: " choice1=raw_input() print"please key in second log file use: " choice2=raw_input() filename1=filenames[choice1] filename2=filenames[choice2] print filename1 print filename2 

*

however, got error : filename1=filenames[choice1] typeerror: list indices must integers, not str.

any advice ? thanks!

you have first convert input int using int()

print "please key in first log file use: " choice1=raw_input() . . filename1=filenames[int(choice1)] . 

or convert input straight int

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

you should display list of files corresponding index numbers user know choose.

update

for error handling, can try like

while true:     choice1 = raw_input('enter first file name index: ')     if choice1.strip() != '':         index1 = int(choice1)         if index1 >= 0 , index1 < len(filenames):             filename1 = filenames[index1]             break // breaks while loop when index correct 

and same choice2


Comments

Popular posts from this blog

Unable to remove the www from url on https using .htaccess -