Python sort string Alphabetically | Ways to sort letters of string alphabetically

Use sorted() and str.join() to sort a string alphabetically in Python. Another alternative is to use reduce() method. It applies a join function on the sorted list using the ‘+’ operator.

>>> a = 'ZENOVW'
>>> ''.join(sorted(a))

How to sort a string alphabetically in Python example

Simple Python example code. A program to sort letters of string alphabetically.

Use sorted() and str.join()

def sortString(str):
    return ''.join(sorted(str))

str = 'PYTHON'


Python sort string Alphabetically

Using sorted() with reduce()

from functools import reduce

def sortString(str):
    return reduce(lambda a, b: a + b, sorted(str))

str = 'PYTHON'

Output: HNOPTY

Do comment if you have any doubts and suggestions on this string topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

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.