Sort a Python string
This post will discuss how to sort a string in Python.
Since strings are immutable in Python, you cannot simply shuffle characters in a string to convert it in sorted order. However, you can create a copy of the string in sorted order. This post provides an overview of possible ways to accomplish this in Python.
1. Using sorted() function
A simple solution is to use the built-in function sorted(). Since it returns a new sorted list of characters, you can construct a string using the str.join() function. This would translate to a simple code below:
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': s = 'BCDA' x = ''.join(sorted(s)) print(x) # ABCD |
2. Using reduce operation
Another option is to perform a reduction operation using the functools.reduce function. Here’s an example of its usage:
|
1 2 3 4 5 6 7 8 9 |
from functools import reduce if __name__ == '__main__': s = 'BCDA' x = reduce(lambda x, y: x+y, sorted(s)) print(x) # ABCD |
That’s all about sorting a string in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)