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
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.
0 Comments