Python program to sort out words of the sentence in ascending order


In order to sort the words of a sentence in ascending order, we first need to split the sentence into words using space as the splitting point. For simplicity, we'll only be splitting on space and let the punctuation be there. We can use replace or regex to remove that as well.

Once we split the sentence, we can sort the words lexicographically(like in a language dictionary) using either sort or sorted methods depending on whether we want to sort the array in place or sort it, then return a new array.

In place sorting: when we want to sort the array/list in place, ie, changing the order in the current structure itself, we can use the sort method directly. For example,

Example

sent = "mary has a very beautiful dog"
my_arr = sent.split(" ")
print(my_arr)
my_arr.sort()
print(my_arr)

This will give the output −

['mary', 'has', 'a', 'very', 'beautiful', 'dog']
['a', 'beautiful', 'dog', 'has', 'mary', 'very']

As you can see here, the original array, my_arr has been modified. If you want to keep this array as it is and created a new array when sorting, you can use the sorted method. For example,

 Live Demo

sent = "mary has a very beautiful dog"
# Split on space.
my_arr = sent.split(" ")
print(my_arr)

# Create a new array using the sorted method
new_arr = sorted(my_arr)

print(new_arr)

# This time, my_arr won't change in place, rather, it'll be sorted
# and a new instance will be assigned to new_arr
print(my_arr)

Output

This will give the output −

['mary', 'has', 'a', 'very', 'beautiful', 'dog']
['a', 'beautiful', 'dog', 'has', 'mary', 'very']
['mary', 'has', 'a', 'very', 'beautiful', 'dog']

As you can see here, the original array did not change.

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 20-Jun-2020

941 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements