Search code examples
pythonstringfor-loopformatalphabetical

How do I make a list in alphabetical order and format it properly?


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))

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)