Sort String Alphabetically in Python

Problem Formulation: How to sort a given string alphabetically in Python?

Example:

  • Input String: PYTHON
  • Output String: HNOPTY

Thus, in this article, you will learn about numerous ways to sort and arrange a string alphabetically in Python, as shown in the above example.

✨ Method 1: Using sorted() + join() Methods

📍 sorted() is a function in Python that sorts all the elements of an iterable in a specific order and returns a sorted list of the specified iterable. You can sort the items in ascending or descending order.

Syntax:

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

✏️ Note: You cannot sort an iterable that contains both – numerical and string values.

📍 join() is a method in Python that takes all the items in an iterable and then combines them in one string. You must specify a string as a separator.

Syntax:

string.join(iterable)

Now, let’s use the sorted() and join() methods to sort the given string alphabetically.

Output:

Original String- PYTHON
Sorted String- HNOPTY

Explanation:

  • sorted(text) helped us to sort the given characters of the string in alphabetical order.
  • join() helped us to combine the sorted characters into one string.

The above example sorts the string in ascending order. You can also sort it in descending order using the following syntax:

print(“Sorted String-“, ”.join(sorted(text, reverse=True)))

  • reverse is a Boolean attribute of the sorted() method that generates a sorted output in descending order when it is set to True.

☠️ Caution: Always remember to use the join() method after sorting the strings. Forgetting to do so will result in an output of a sorted list instead of a string, as shown below.

Output:

Original String- PYTHON
String 1- [‘H’, ‘N’, ‘O’, ‘P’, ‘T’, ‘Y’]

✏️ You can also use the set() method to only display unique letters in the sorted string. In Python, sets are an unordered collection of the unique elements. Thus, it eliminates all the duplicate values.

Example:

Output:

Original String: consequences
Sorted String: cenoqsu

💡 How will you sort a string that contains both – uppercase and lowercase characters?

Solution: You can use to a lambda function within the sorted method to achieve this task.

Output:

iIiIMPpSssS

✨ Method 2: Convert The String to List And Sort

In Python, strings are immutable, and lists are mutable.

Hence, we can sort the string by converting it into a list first. We will then use a sorting algorithm (insertion sort or bubble sort) to sort the converted list. Finally, we will convert the sorted list to a string and print the output.

Example:

Output:

Enter a string: PYTHON
The sorted string is: HNOPTY

Method 3: Using The reduce() Method

  • reduce() is function of the functools module in Python.
  • It takes a function and a list as an argument.
  • When it is called with a lambda function and an iterable, it performs a repetitive operation over the pairs of the iterable. 

Output:

Enter a String: Python
String 2: InputString
Sorted String 1: hnopty
Sorted String 2: giinnprsttu

Explanation:

  • To use the reduce method, you have to import it from the functools module.
  • sorted(text.lower()) –> converts all the characters to lowercase and then sorts them alphabetically in a list.
  • the reduce function then accepts the lambda function and the list containing sorted characters of the string as inputs. It then applies the join function on the sorted list with the help of + operator.

Method 4: Using The accumulate() Function

✏️ accumulate() is a function of the itertools module in Python. It takes two arguments as an input, i.e., an iterable and a function that will be implemented at each iteration.

#Note: If no function parameter is mentioned, then by default accumulate will perform an addition operation.

Syntax:

itertools.accumulate(iterable[, [func])

You can use the accumulate function to sort the given string as shown in the following example:

Output:

HNOPTY

Explanation:

  • To be able to use the accumulate function, you have to import it from the itertools module.
  • sorted(text) will sort the string in alphabetical order.
  • Now let’s visualize what happens in each iteration within the accumulate function when you store the result of accumulate(sorted(text)) in a list:
  • Finally, select the last index of the list to print the output –> li[-1]

Read here: Python String Compare

Conclusion

I hope this article managed to guide you through all the methods that can be used to sort a string alphabetically in Python. Please stay tuned and subscribe for more tutorials.

Happy learning! 📚

Author: Shubham Sayon
Co-author: Rashi Agarwal

Related Posts

  • How to comment out multiple lines in python
    16 October

    How to comment out multiple lines in python

    Table of ContentsMultiple Line Comments in PythonUsing the # characterUsing triple quotesUsing IDEs and Text Editors In this article, we will see about how to comment out multiple lines in python. The concept of comments is present in most programming languages. We use comments for documentation purposes. The compiler ignores them, but the user can […]

  • Get variable name as String in Python
    01 October

    How to get variable name as String in Python

    Table of ContentsWhat are variable names in Python?How to get a variable name as a string in Python?In Python 2.xIn Python 3.x In Python, there are several ways to convert a string to a variable name, but the reverse process is not exactly utilized so often in the programming world. This article focuses on how […]

  • Python print percent sign
    30 September

    Print percentage sign in python

    Table of ContentsIntroductionPrint the Percentage Sign in PythonUsing the %% characterUsing the format() functionUsing the f-string Introduction In this tutorial, we will see how to print percentage sign in python. The modulus operator (%) or the percentage sign has multiple usages in Python. We use this operator to calculate the remainder for the division between […]

  • Print blank line in Python
    23 September

    Print blank line in Python

    Table of ContentsWhat is a blank line in Python?Ways to print blank line in PythonUsing an empty print() functionUsing the print() function with newline characterUsing the print() function with an empty stringUsing the print() function with the sep parameterWays to print multiple blank lines in PythonUsing the print() function with multiple newline charactersUsing the print() […]

  • 17 September

    Write list to CSV in Python

    Table of ContentsUsing the write() function to write a list to a CSV fileUsing the csv module to write a list to a CSV fileUsing the numpy module to write a list to a CSV fileUsing the numpy.savetxt() function to write a list to a CSV fileUsing the numpy.tofile() function to write a list to […]

  • Python add commas to number
    11 September

    Python add commas to number

    Table of ContentsUsing the format() function to add commas to numbers in PythonUsing the fstrings to add commas to numbers in PythonUsing the regular expressions to add commas to numbers in PythonUsing the locale module to add commas to numbers in Python Python allows us to format values to get the final result in our […]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.