Skip to content

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

  • by

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))
'ENOVWZ'

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'
print(sortString(str))

Output:

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'
print(sortString(str))

Output: HNOPTY

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

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

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