
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sort Letters in a String Alphabetically in Python
In Python, Sorting the string alphabetically is a common task helps for string manipulation or text analysis. It is used in creating the anagrams, checking for permutations, or standardizing the input for consistent processing, for example, turning 'banana' into 'aaabnn'.
In this article, we will explore how to sort the letters in a string alphabetically, this can be done by using the Python built-in function.
Using Python sorted() Function
The Python sorted() function is used to return a new sorted list from the items in the iterable object. The order of sorting can be set to either ascending or descending.
In this approach, we are passing a string to the sorted(), which treats the string as a sequence of characters and returns the characters sorted in alphabetical order.
Syntax
Following is the syntax of the Python sorted() function -
sorted(iterable, key=key, reverse=reverse)
Example 1
Let's look at the following example, where we are going to consider the basic usage of the sorted() function.
str1 = "tutorialspoint" result = ''.join(sorted(str1)) print(result)
The output of the above program is as follows -
aiilnooprstttu
Example 2
Consider the following example, where we are going to sort a string with the uppercase letters 'WelcoMe'.
In this scenario, it uses the ASCII values to sort the characters. So, the uppercase letters come before the lowercase letters same will be observed in the output.
str1 = "WelcoMe" result = ''.join(sorted(str1)) print(result)
The output of the above program is as follows -
MWceelo
Example 3
In the following example, we are going to sort the string with the spaces.
In this scenario, as we use space in the input string, they will come first because of their lower ASCII values, and the same is observed in the output.
str1 = "Hi Hello" result = ''.join(sorted(str1)) print(f"'{result}'")
The output of the above program is as follows -
' HHeillo'
Using sorted() and sets
The second approach is by using the sorted() method and sets. This is similar to the above approach, but this is used if you want to have only Unique characters as output. We just need to send the string as a set.
Example
Following is an example, where we are going to sort the string and return only the unique characters.
str1 = "TutorialsPoint" res = ''.join(sorted(set(str1))) print(res)
The following is the output of the above program -
PTailnorstu