Salina Karki
Salina Karki

Reputation: 11

Role of space while sorting words

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

Answers (4)

faiz-e
faiz-e

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

Mike Organek
Mike Organek

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

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

sushanth
sushanth

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

Related Questions