1

if the data in the text file has is less than 10 (for example 4,2,3,1) it will sort the data accordingly. However, if the data is more than 10 (for example (3,199,4,5), it will sort to 199,3,4,5 instead of ascending order. Please help

def readFile():
        try:
            fileName = open("haha.txt",'r')
            data = fileName.read().split()
            data.sort() 
            print(data)

        except IOError:
                    print("Error: File do not exist")
                    return
1
  • 1
    Wow! You've discovered a completely obvious bug in a widely used piece of software!! Or...maybe not. The problem, as others have said, is that you're sorting character strings, and sort may not behave as you expected. As a general rule you might want to consider that whenever you think you've found that really obvious bug in a widely used piece of software, it may be that you're mistaken in your understanding of the software. In 40+ years of software development I've found very, very few actual bugs. I have, however, found many, many failures in my understanding. YMMV. Best of luck. Commented Dec 29, 2015 at 1:34

2 Answers 2

8

You are sorting strings lexographically, and the 1 character has a lower value than the 3 character. Adding ,key=int to the sort function would fix this.

data.sort(key=int)
1
  • Thank you sir. This helped alot! Commented Dec 29, 2015 at 1:35
1

Because items in data are strings, you can turn the item into ints by:

data = [int(item) for item in data]

Not the answer you're looking for? Browse other questions tagged or ask your own question.