Reputation: 11
I was playing through a python code to sort the words alphabetically. I realized when I write "," and ", " the output changes. This might be basic but can anyone help me understand why this happens?
1st case:
My code:
string = input("enter comma separated sequence of words: ").split(",")
string = sorted(string)
print(','.join(string))
Output: enter comma-separated sequence of words: red, white, black, red, green, black
Sorted: black, black, green, red, white,red
2nd case:
My code:
string = input("enter comma separated sequence of words: ").split(", ")
string = sorted(string)`enter code here`
print(', '.join(string))
Output: enter comma separated sequence of words: red, white, black, red, green, black
Sorted: black, black, green, red, red, white
Upvotes: 0
Views: 602
Reputation: 210
All answers are good. I have just added a case where user might enter empty spaces between commas...like A,Z, ,C. The following code covers this case too.
words = input("enter comma separated words here: ")
wordsList= [x.strip() for x in my_string.split(',') if x.strip() !=""]
sortedWords = ','.join(sorted(result))
return sortedWords
Upvotes: 0
Reputation: 12484
When you split on only the comma (","
) the space that trails the comma is retained as the first character of the word following the comma.
The first word in the list, red
, does not have a leading space. When collating, a space character sorts ahead of any letter. All the color names appear first as sorted with the leading space and are followed by the red
that has no leading space.
Perhaps this will help illustrate:
>>> string = input("enter comma-separated sequence of words: ").split(",")
enter comma-separated sequence of words: red, white, black, red, green, black
>>> string = sorted(string)
>>> for s in string:
... print(f"[{s}]")
...
[ black]
[ black]
[ green]
[ red]
[ white]
[red]
>>>
Upvotes: 0
Reputation: 99
you only need to split the words by the space between the words. Try this:
my_string = input("enter words here: ")
result = [x.strip() for x in my_string.split(',')]
print (','.join(sorted(result)))
Hope it helps you!!
Upvotes: 0
Reputation: 8302
Try this, it looks like there are spaces causing the issue.
string = input("enter comma separated sequence of words: ").split(",")
string = sorted(string, key=lambda x : x.strip())
print(','.join(string))
Upvotes: 2