0

I am just learning python and I came across a code for sorting words alphabetically.

My code is:

my_str="Welcome to Python"
words = my_str.split()
words.sort()
print("The sorted words are:")
for word in words:
    print(word)

My result comes out as:

The sorted words are:

Python

Welcome

to

I mean it is sorted alphabetically then it should result as

Python

to

Welcome

I am totally confused and unable to proceed forward in learning process, your insights would be so helpful.

Humayun Ahmad Rajib
  • 1,502
  • 1
  • 10
  • 22
sachin
  • 11
  • 1
  • 3
    Capital letters come before small letters in ASCII – rdas Apr 29 '20 at 04:29
  • To sort case-insensitively, you can use [`str.casefold`](https://docs.python.org/3/library/stdtypes.html#str.casefold). Something like `some_list.sort(key=str.casefold)`. – jirassimok Apr 29 '20 at 04:32

2 Answers2

0

capital letters are smaller that small letter

>>> 'A' < 'a'
True

If you want to sort without making a distinction between capital and small letters use this.

>>> words.sort(key=str.lower)
>>> words
['Python', 'to', 'Welcome']

If you are using python3 you can use str.casefold for comparison this will handle unicode comparison as well.

>>> words.sort(key=str.casefold)
>>> words
['Python', 'to', 'Welcome']
Albin Paul
  • 3,330
  • 2
  • 14
  • 30
  • You can just use `str.lower` instead of a lambda, or [`str.casefold`](https://docs.python.org/3/library/stdtypes.html#str.casefold), which is specifically for caseless comparison, and handles Unicode properly. – jirassimok Apr 29 '20 at 04:33
  • thank you so much, that helped to clear my mind. – sachin Apr 29 '20 at 04:39
0

You can try it:

my_str="Welcome to Python"
some_list = my_str.split()
some_list.sort(key=str.casefold)

print("The sorted words are:")
for word in some_list:
    print(word)

Output will be:

Python
to
Welcome
Humayun Ahmad Rajib
  • 1,502
  • 1
  • 10
  • 22