Search code snippets, questions, articles...

Python Sort String: Quick and Easy Guide

Python is a programming language that is widely used by web developers and software engineers. Python's simple syntax and powerful data structures make it an ideal language for sorting strings. This quick and easy guide will show you how to sort strings in Python.

Sort a String using sorted() and join() functions

Python provides a number of built-in functions for working with strings, including the sorted() and join() functions.

The sorted() function can be used to sort a string alphabetically, while the join() function can be used to join together a list of strings into a single string. Together, these functions can be used to sort a string alphabetically.


Code example - Sort string in ascending order

input_str = 'programming'

result_str = ''.join(sorted(input_str))

print(f'The original string is: {input_str}')
print(f'The sorted string is: {result_str}')

Output

The original string is: programming
The sorted string is: aggimmnoprr
  1. In the above code example, we have created a string variable called input_str and assigned the string 'programming' to it.
  2. Then we created a string variable called result_str and assigned to it the result of running the string method sorted on input_str. sorted returns a list of the characters in input_str in alphabetical order, which is then joined into a string using the join() method.
  3. Then we print the original string and the sorted string to the console.

Code example - Sort string in descending order

input_str = 'programming'

result_str = ''.join(sorted(input_str, reverse=True))

print(f'The original string is: {input_str}')
print(f'The sorted string is: {result_str}')

Output

The original string is: programming
The sorted string is: rrponmmigga

In the above code example, we are sorting the string in descending order. We are using reverse=True in the sorted() function to do that.


Was this helpful?
0 Comments