×

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

How to Plot Graphs Using Python?

In this article, we are going to learn about how to plot different types of graphs using Python. We are going to use different approaches for every type of graph....

3 minutes read.

Kite Python

Kite in Python: The Kite is a package provided by the python programming language; it works with the help of artificial intelligence and helps us write code inside the visual studio....

3 minutes read.

Python abs() function

Python abs() function The abs() function returns the absolute value of a number. Syntax abs(x) Parameter x: The parameter ‘x’ can be an integer value, a floating point number or a complex number. Return This function returns...

1 minute read.

How to set font for Text in Python

As a tuple with the font family as the first component, a size in point as the second, and possibly a string with one or more of the style modifiers...

5 minutes read.

Python Encapsulation

What is meant by Encapsulation? The process of restricting access to the methods and variables so that accidental modification of data can be prevented is known as Encapsulation. The motive of Encapsulation:...

3 minutes read.

Exponentiation in Python

What is an Exponent in Python? Exponent is a fundamental mathematical concept that is used in many different areas, such as engineering, physics, and finance. In mathematics, an exponent is a...

4 minutes read.

Conditional Statements in python

In this article, we will learn about conditional statements and how to apply conditional statements in Python. A decision-making statement is another name for a conditional statement. Decision-making is an important...

5 minutes read.

Shallow Copy and Deep Copy in Python

Shallow Copy and Deep Copy in Python In this section, we will learn about the Shallow Copy and Deep Copy in the Python program. But before going through the topic, we...

6 minutes read.

How to make a firewall in Python?

Firewall: The firewall is a network which controls the incoming and outgoing network traffics of a monitor. It blocks the dataset based on the set of rules written in the security...

3 minutes read.

Time. Sleep() in Python

Python time sleep () function suspends execution for a certain seconds given by user. Time sleep () syntax: Sleep(seconds) Limitations: The number of seconds to be suspends the code as per its requirements. Returns: Void The execution...

3 minutes read.

FOO 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...

3 minutes read.

Python Dictionary setdefault() method

Python Dictionary setdefault() method The dictionary.setdefault () method in Python returns the value of the item with the specified key. Syntax dictionary.setdefault(keyname, value) Parameter keyname- This parameter represents the keyname of the item you want...

1 minute read.

First Unique Character in a String Python

This article aims to introduce you to strings and how to create a string in Python, and then we will solve a simple yet exciting DSA (Data Structures and Algorithms)...

3 minutes read.

Python zip() Function

Python zip() Function The zip() function makes an iterator that aggregates elements from each of the iterables and returns an iterator of tuples. Syntax zip(*iterables) Parameter iterables: Iterator objects that will be joined together Return This function...

1 minute read.

Python Program to Print Sum of all Elements in an Array

Python program to print sum of all elements in an array A set of objects stored in contiguous memory locations is referred to as an array. The concept is to keep...

2 minutes read.

Python len() function

Python len() function The len() function in Python  returns the number of items in an object. Syntax len(s) Parameter s: This parameter represents a sequence (such as a string, bytes, tuple, list, or range) or...

1 minute read.

Mrcnn 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 coding platform

Python is a popular general-purpose programming language with many applications. High-level data structures, datatypes, dynamic binding, and many other features make it useful for both designing complex applications and "glue...

6 minutes read.

Algorithm for Factorial of a number in Python

What is a Factorial Number? In mathematics, the factorial of a positive integer n, denoted by n!. It is the product of all positive integers less than or equal to n. For...

3 minutes read.

Data Structures and Algorithms Using Python | Part 1

Data Structures: Data Structure is defined as a way to organize and store the data so that we can access the data and work more efficiently. Data structures also describe the...

18 minutes read.