tyroneH
tyroneH

Reputation: 27

Reading lines from a list starting with a user-inputted letter?

To note: Some classmates told me that I HAVE to take userInput to create another list based on the userInput. (Eg: Input "g", Creates list with countries that starts with "g".)

This is my current code.

countries = []
population = []
str = []
path = "E:\\SCRIPTING\\Countries.txt"
obj = open(path, "r")
allList = obj.readlines()
obj.close()
userI = input("Please input a single letter: ")
if userI.isalpha():
    if len(userI) > 1:
        print("Please enter only a single letter.")
    else:
        print("continue")
elif userI.isdigit():
    int(userI)
    print("Please enter a single letter, not a number.")
else:
    print("Please make sure that you enter a single letter.")

So far from what I have I know that it's reading my .txt file, and displaying different errors/messages when incorrect inputs are given. (Program to be put under the else: print("continue) since its my checkpoint.

The program is made to accept only 1 letter and print all lines which start with that letter.

Upvotes: 0

Views: 53

Answers (2)

0xc0de
0xc0de

Reputation: 8287

You are not actually applying the main logic, you have done the input handling, file opening correctly.

You need:

else:
    # Bad variable name, see python.org/dev/peps/pep-0008/#id36
    for line in allList
        if line.startswith(userI):
            print line

elif userI.isdigit():

UPDATE:

There is one more change I suggest, after looking at your updated code:

# raw_input() instead of input()
userI = raw_input("Please input a single letter: ")

Apart from that, I have tested your code and it works provided that there is text data in the file pointed by path. Also another note, startswith is case sensitive, so make sure you give alphabet in correct case as the text in file.

Upvotes: 0

iFlo
iFlo

Reputation: 1484

You could return a list with a simple test, just before your :

print("continue")

You could add those lines

listToBeDisplayed = [line for line in allList if line.startswith(userI)]
for line in listToBeDisplayed :
    print line

Upvotes: 1

Related Questions