×

How to Sort a String in Python?

The characters in the string are sorted or put in alphabetical order using the sort string function in Python. Python has built-in techniques for sorting strings available. Since we occasionally need to sort data based on a customer name in ascending or descending order, Python provides the sort methods for this purpose. Sorting strings has always been a very common utility with many applications worldwide. Containers can be sorted in Python using the two methods, sort() and sorted().

The sorted() method creates a new sorted list from an original list, whereas the sort() method adjusts the list while it is already in place.

Python sort string sorted() function syntax:

sorted(iterable, key = key, reverse = reverse)

Parameters:

  • Iterable: This is a list of strings that must be sorted; it is not an optional argument.
  • Key: This parameter can provide the functionality to execute to select the sort order. None is the default value.
  • Reverse: The Boolean argument specifies whether the order should be ascending or descending. False indicates descending order, while True indicates ascending order. Here, False is the default setting.

Value Returned:

This method returns a sorted string as its result.

Python's sort string functionality

Python's sort string function accepts a string as a parameter, compares each character in the string based on its ASCII value, and then returns a list of the string's sorted characters.

Python examples of sorting strings

The suggested instances are shown below:

Example 1: Use Python's built-in sorted() method to sort a string.

# making a string
msg = "Hello!, how are you"
print("The original message is : ")
print(msg)
# getting a list of sorted characters using the sorted() method
alt_msg = sorted(msg)
print( "The output of the sorted() method is :  " )
print( alt_msg )
# getting a list of sorted characters using the sorted() method
sort_msg = "".join(alt_msg)
print( "The sorted message is :  " )
print( sort_msg )

Output:

The original message is:
Hello! how are you
The output of the sorted() method is:
[', '', '', ''!', ', ''H,' 'a', 'e,' 'e,' 'h,' 'l,' 'l,' 'o', 'o', 'o', 'r,' 'u,' 'w,' 'y']
The sorted message is:
          !,Haeehlloooruwy

The same string variable that stores the "Hello! how are you" is generated in the program. The sorted() method, which returns a sorted list of string characters, is then used in the program (as displayed in the output). The join() method returns the string of sorted characters and is then used to join the sorted list of characters. As a result, the final sorted string still contains all the characters from the original string but in a different order. Because the space character's ASCII value is lower than all the other characters in the string, it is the first character in the sorted string.

Example 2: A Python while loop is used to sort a string.

# making a string
string = "Sample string to sort alphabetical order."
print( "The original string is : " )
print( string )
# getting a list of sorted characters in ascending order using the sorted() function
list_string=list( string )
print( "The list of string is : " )
print( list_string )
list_string = list(string)
i = 0
while i < len( list_string ):
key = i
j = i+1
while j < len( list_string ):
if list_string[key] > list_string[j]:
key = j
j += 1
list_string[i],list_string[key] = list_string[key],list_string[i]
i += 1
print( "The list of sorted string is : " )
print( list_string )
new_string = "".join(list_string )
print( "The sorted string is : " )
print(new_string)

Output:

The original string is:
Sample string to sort in alphabetical order:
The list of the string is as follows:
[‘s’, ‘a’, ‘m’, ‘p’, ‘l’, ‘e’, ‘ ‘, ‘s’, ‘t’, ‘r’, ‘I’, ‘n’, ‘g’, ‘ ‘, ‘t’, ‘o’, ‘ ‘, ‘s’, ‘o’, ‘r’, ‘t’, ‘ ‘, ‘a’, ‘l’, ‘p’, ‘h’, ‘a’, ‘b’, ‘e’, ‘t’, ‘I’, ‘c’, ‘a’, ‘l’, ‘ ‘, ‘o’, ‘r’, ‘d’, ‘e’, ‘r’, ‘.’]
The last sorted string is:
[‘   ‘,  ‘  ‘,  ‘  ‘,  ‘  ‘,  ‘  ‘,  ‘  .’,  ‘  s ‘,  ‘ a ‘,  ‘ a ‘,  ‘ b ‘,  ‘ c ‘,  ‘ d ‘,  ‘ e ‘,  ‘ e ‘, ‘ e ‘,  ‘ g ‘, 
' h, '' I, '' I, '' l, '' l, '' m, '' n, '' o, '' o ',  '  o ',  ' p ',  ' p ',  ' r ',  ' r ‘, ‘ s ‘, ‘ s ‘, ‘ t ‘, ‘ t ‘, ‘ t ‘, ‘ t ‘ ]
The sorted string is:
     .Saaaabcdeeeghiilllmnooopprrrrsstttt

The phrase "Sample string to sort alphabetically" appears in the abovementioned program. Without utilising the sorted() method, is sorting. Similar to the program above, which compares each character using a while loop, the first while loop ensures that the loop iteration should be smaller than the length of the string before taking each element in turn and comparing and swapping them in the second while loop. Therefore, a sorted list of string characters is returned. The join() method is then used to join the sorted list of characters. As a result, the final sorted string still contains all the characters from the original string but in a different order.

Example 3: Show how to build bubble sort in Python by using a “for loop” to sort a text.

# making a string
string = "This is a sample string"
new_string = []
print( "The original string is : " )
print( string )
# To obtain a list of sorted characters without using the sorted() function
list_string=list(string)
print( "The list of string is : " )
print(list_string)
list_string=list(string)
len_s=len(list_string)
for i in range(len_s-1):
for j in range(len_s-i-1):
if list_string[j]>list_string[j+1]:
list_string[j],list_string[j+1]=list_string[j+1],list_string[j]
For m in list_string:
new_string+=m
print( "The list of sorted string is : " )
print(new_string)
sort_string = "".join(new_string)
print( "The sorted string is : " )
print(sort_string)

Output:

The original string is :
This is a sample string
The list of the string is as follows:
[‘T’,  ‘h’,  ‘I’,  ‘s’,  ‘ ‘,  ‘I’,  ‘s’,  ‘  ‘,  ‘I’,  ‘s’,  ‘  ‘,  ‘a’,  ‘ ‘,   ‘s’,  ‘a’,  ‘m’,  ‘p’,  ‘l’,  ‘e’,  ‘ ‘, ‘s’,  ‘t’,  ‘r’,  ‘I’,  ‘n’,  ‘g’]
The list of the sorted string is as follows:
[‘ ‘,  ‘ ‘,  ‘ ‘,  ‘ ‘,  ‘T’,  ‘a’,‘a’,  ‘e’,  ‘g’,  ‘h’,  ‘i’,  ‘i’,  ‘i’,  ‘l’,  ‘m’,  ‘n’,  ‘p’,  ‘r’,  ‘s’,  ‘s’,  ‘s’, ‘s’  ‘t’]
The sorted string is:
        Taaeghiiilmnprsssst

The string "This is a sample string" is sorted similarly to the program above without using the sorted() method. The program uses a “for loop” to compare each character. If the previous character is greater than the following character, a swap is made; otherwise, there is no swap. Consequently, it provides a sorted list of string characters (as displayed in the output). The join() method, which returns an ascending string, is then used to join the sorted list of characters. As a result, the final sorted string still contains all the characters from the original string but in a different order.

Sorting a string with sorted() + reduce() + lambda

When reducing an iterable to a single cumulative value after applying a function to it, the reduce() method is useful. The function defined in Python without a name is called a lambda function.

Combine the sorted(), reduce(), and lambda functions to sort a text alphabetically. Reduce() is not a built-in function in Python. Therefore, we must import the fun tools package containing the reduce() function.

Example:

import functools
data = "immunoelectrophoretically"
print("The original string is : " + str(data))
sorted string = functools.reduce(lambda x, y: x + y, sorted(data))
print("String after sorting : " + str(sortedString))

Output:

The original string is: immunoelectrophoretically
String after sorting: acceeehiilllmmnoooprrttuy

Python reverse string sorting instructions

Use the sorted() and join() functions in Python and supply the reverse = True option to the sorted() function to sort a string in reverse order.

Example:

data = "immunoelectrophoretically"
print("The original string is : " + str(data))
reverse sorted = ''.join(sorted(data, reverse = True))
print("The reverse sorted string: ",reverse sorted)

Output:

The original string is: immunoelectrophoretically
The reverse sorted string: yuttrrpooonmmllliiheeecca

You can see that it gave back a reverse-sorted string in the output.


Related Topics

Calculator Program in Python

Simple Calculator Program in Python This example helps to learn how to create a simple calculator program to perform operations like addition, subtraction, multiplication, and division. Source Code The following is the source...

2 minutes read.

How to Convert Int to String in Python?

Every value we use or store in a variable in Python will have a specific data type. It describes the value's nature; based on that, Python will automatically assign a...

4 minutes read.

ER diagram of the Bank Management System in python

What is an ER diagram? The full form of the ER diagram is the Entity Relationship diagram. This diagram is used in database management systems to have a rough idea of...

3 minutes read.

Yield vs Return in Python

In this article, you will learn about " Yield " and " Return " in Python. You will also understand the difference between " Yield " and " Return "...

6 minutes read.

Syntax of Map function in Python

In this tutorial, we will understand what the map function in Python is meant. Further, we will see the syntax to be used for the same in python language. We...

3 minutes read.

Python Selectors

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

4 minutes read.

Looping through Data Frame in Python

Iterate over Rows and Columns in Pandas Dataframe This tutorial aims to make us understand what Pandas in Python are, what Data Frame in Python is and its significance, what are...

4 minutes read.

Find Median of List in Python

The median is an enlightening measurement that is utilized as a proportion of the focal inclination of a circulation. It is equivalent to the centre worth of the conveyance. There...

3 minutes read.

Convert XML to JSON in Python

XML conversion is very useful if we work on an API that returns data in JSON format and the source of data is in XML format. JSON A JSON file reserves the...

4 minutes read.

Python comment symbol

Python programmers frequently use the comment system because, without it, things may quickly become very perplexing. The developers' helpful information is provided in the comments, which helps the reader understand...

3 minutes read.

Python Stack

Python Stack: The work Stack is defined as arranging a pile of objects or items on top of another. It is the same method of allocating memory in the stack...

10 minutes read.

Excel Automation with Python

Data analysis is the upcoming technology in the IT sector; this data analysis can be performed easily with the help of data frames or by using excel sheets. The data...

4 minutes read.

Gethostbyname() function in Python

Python Programming Language Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

6 minutes read.

Python Win32 Process

The Win32 process is essentially a Python procedure. This program provides access to advanced Win32 process creation and management features. Process objects are created through the Create method (the constructor)....

6 minutes read.

Python JSON

In this tutorial, we will learn about JSON in the Python programming language. We will focus on its features, Guidelines to be kept in mind while writing its syntax, the...

3 minutes read.

Python Empty Tuple

How to Create an Empty Tuple Tuple A tuple is a data structure used to store non-homogeneous data elements. These non-homogeneous data elements consist of integer data type, character data type, String...

3 minutes read.

Python program to find the area of the triangle

Python program to find the area of the triangle This article will discuss how to find the area of a triangle in Python with all three given sides. The area of...

2 minutes read.

Applications of Python

Top 10 Applications of Python in 2020- 2021 Python language is famous for its general-purpose nature, which enables developers to use it in every field of development. Python can be found...

6 minutes read.

Python JSON Schema

Python-jsonschema JSON: JSON stands for JavaScript Object Notation. It is a text-based format that represents structured data and can be used to interchange data among various applications. This is self-defining language...

5 minutes read.

Python List reverse() method

 Python List reverse() method The list.reverse () method in Python reverses the elements of the list in place. Syntax list.reverse() Parameter NA Example 1 # Python program explaining # the list.reverse() method weekList = ['Sun','Thurs','Mon','Fri', 'Tues', 'Wed'] print("Actual week list: ",weekList) #...

1 minute read.