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

  • Detect keypress in Python
    12 June

    Detect keypress in Python

    Table of ContentsUsing the keyboard module to detect keypress in PythonUsing the pynput module to detect keypress in PythonUsing the msvcrt module to detect keypress in Python Python allows us to work with user input in its programs. We can also work with hardware devices in Python. In this article, we will discuss how to […]

  • Copy a dictionary in Python
    12 June

    7 ways to copy a dictionary in python

    Table of ContentsUsing the copy() function to copy a dictionary in PythonUsing the deepcopy() function to copy a dictionary in PythonUsing the dict() function to copy a dictionary in PythonUsing the unpack operator ** to copy a dictionary in PythonUsing the update() function to copy a dictionary in PythonUsing the dictionary comprehension method to copy […]

  • Escape quotes in Python
    11 June

    Escape quotes in Python

    Table of ContentsUsing \ to escape quotes in PythonUsing \ with replace() to escape quotes in PythonUsing json.dumps to escape quotes in PythonUsing triple single or double quotes to escape quotes in pythonUse r to include \ and quotes in String 💡 Outline You can use \ to escape quotes in Python. If you want […]

  • Sleep for milliseconds in python
    31 May

    How to sleep for milliseconds(ms) in Python

    Table of ContentsUse time.sleep() function to make the program sleep for millisecondsUse threading.Timer() function to make the program sleep for milliseconds 💡 Outline You can use time.sleep() method to sleep for milliseconds in Python. If you want to delay python program by 500 ms, then you need to pass 0.5 as parameter to sleep method. […]

  • Convert unix timestamp to datetime in Python
    21 May

    Convert Unix timestamp to DateTime in python

    Table of ContentsUsing fromtimestamp() FunctionUsing strftime() FunctionUsing to_datetime() Function A UNIX timestamp is defined as the several numbers of seconds between a particular date and the Epoch i.e January 1, 1970 at UTC. In this tutorial, we will see some methods by which we can convert a UNIX timestamp to DateTime in Python. Using fromtimestamp() […]

  • Python round to 2 decimal places
    21 May

    How to round to 2 decimals in Python

    Table of ContentsUsing the round() functionUsing the format() functionUsing the % formattingUsing the f-stringsUsing the math.ceil() and math.floor() functions In Python, we deal with integers, floating values, and even imaginary numbers. Float numbers are used to represent the real numbers with integers and decimal parts. Python represents such numbers with 64-bit precision giving it a […]

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.