Reputation: 7
For example, if a .txt file consists: car and day
I want to make them in alphabet order: acr adn ady
Here's what I have in my code right now:
def read_file(fileName):
list = []
with open(fileName) as f:
list = f.read().split()
list.sort()
return list
It just won't sort the way I want, do I need a nested for loop?
Upvotes: 0
Views: 52
Reputation: 168
Instead of list.sort():
# don't use `list` as variable
lyst = f.read().split()
" ".join(["".join(sorted(list(i))) for i in lyst])
Upvotes: 0
Reputation: 15249
You need to sort the letters of each word, not the words themselves:
string = "car and day"
" ".join(["".join(sorted(word)) for word in string.split()])
Upvotes: 1
Reputation: 6556
It seems you need this:
def read_file(fileName):
with open(fileName) as f:
a_list = f.read().split()
result = ' '.join([''.join(sorted(a)) for a in a_list])
return result
Upvotes: 2