Question

I have a project question that says "Write a method that takes the user entered words/strings and sort them into alphabetical order."
I have the basic method worked out, but the problem is I need to format it like this:

1#....................(input1)
2#....................(input2) 

for however many inputs they enter.
I can't quite figure out how to format it! I already have the counter in a for loop, but I'm not sure where to go from there.

def wordSort(wordList):
    sortedList = sorted(wordList)
    return sortedList

wordList = []

while True:
    word = raw_input("Please enter a word").title()

    if word == "*":
        break
    wordList.append (word)


print ("The words you are listed in alphabetical order are:")


wordSort(wordList)

sum = 0

for x in wordSort(wordList):
    sum = sum + 1

print ("#%d %s") %(sum, wordSort(wordList))
Was it helpful?

Solution

To fix your code, you can do this:

sortedWords = wordSort(wordList)
for x in sortedWords:
    print ("#%d %s") %(sum + 1, sortedWords[sum])
    sum = sum + 1

You can make it simpler using enumerate():

sortedWords = wordSort(wordList)
for i, word in enumerate(sortedWords):
    print ("#%d %s") %(i, word)

OTHER TIPS

How about http://docs.python.org/2/library/functions.html#enumerate ?

Then iterate over the sorted and enumerated list

Ps: i would not define wordSort just to delegate to sorted.

def get_words():
    words = []
    while True:
        word = raw_input('Please enter a word (or Enter to quit): ').strip().title()
        if word:
            words.append(word)
        else:
            return words

def main():
    words = get_words()

    print ("The words you entered, in alphabetical order, are:")
    for i,word in enumerate(sorted(words), 1):
        print('#{:>2d} {:.>16}'.format(i, ' '+word))

if __name__=="__main__":
    main()

which results in

Please enter a word (or Enter to quit): giraffe
Please enter a word (or Enter to quit): tiger
Please enter a word (or Enter to quit): llama
Please enter a word (or Enter to quit): gnu
Please enter a word (or Enter to quit): albatross
Please enter a word (or Enter to quit): 
The words you entered, in alphabetical order, are:
# 1 ...... Albatross
# 2 ........ Giraffe
# 3 ............ Gnu
# 4 .......... Llama
# 5 .......... Tiger
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top