Python sort string | alphabetically letters ascending/descending order

You can sort string in python using “join() + sorted()” and “sorted() + reduce() + lambda” method combinations. String can sort the letter/characters in ascending or descending alphabetically order.

Example of Python sort string

Let’ see the example program in both ways.

1. Using join() + sorted()

First sorted list of characters and then join the result to get the resultant sorted string.

str1 = "BADCGEHF"

# using join() + sorted()
# Sorting a string
result = ''.join(sorted(str1))

# print result
print(result)

Output:

Python sort string alphabetically letters ascending descending order

2. Using sorted() + reduce() + lambda

It’s Works only for Python2, in the example join the resultant sorted list of characters using the lambda function joined by the reduced function.

from functools import reduce

str = "BADCGEHF"

# using sorted() + reduce() + lambda
# Sorting a string
result = reduce(lambda x, y: x + y, sorted(str))

# print result
print("String after sorting : " + result)

Output: ABCDEFGH

Python sort string lexicographically

Given a string, we need to sort the words in lexicographical order.

def lexicographi_sort(s):
    return sorted(sorted(s), key=str.upper)

print(lexicographi_sort('EyeHunts'))

Output: [‘E’, ‘e’, ‘H’, ‘n’, ‘s’, ‘t’, ‘u’, ‘y’]

Q: How to arrange string in ascending order in python

Answer: You can do it using the join and sorted function. See below example:-

str = 'BADCGEHF'

print(''.join(sorted(str)))

Output: ABCDEFGH

Q: How to sort a string alphabetically in Python?

Answer: Call sorted(iterable) with a string as iterable to return a list of the characters of the string sorted alphabetically. Use str.join(iterable) with "" as str and this list as iterable to create a sorted string.

a_string = "cba"

sorted_char = sorted(a_string)

a_string = "".join(sorted_char)

print(a_string)

Output: abc

Do comment if you have any other way to do it or suggestions or doubts in this tutorial.

Note:
IDE: PyCharm 2020.1.1 (Community Edition)
macOS 10.15.4
Python 3.7
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.