Python Sort String Alphabetically
In Python, we can use the built-insorted()function to sort the characters in a string alphabetically.sorted()The function returns a list containing the characters in ascending order. If we want to get a sorted string, we can usejoin()method to join the characters in the list.
Example
# Original string
original_string = "python"
# Sort the string
sorted_string = ''.join(sorted(original_string))
# Output the sorted string
print(sorted_string)
original_string = "python"
# Sort the string
sorted_string = ''.join(sorted(original_string))
# Output the sorted string
print(sorted_string)
Code explanation:
original_string = "python": Define an original string"python"。sorted(original_string): Usesorted()function to sort the characters in a string, returning a list of characters arranged alphabetically.''.join(sorted(original_string)): Usejoin()method to join the sorted character list into a new string.print(sorted_string): Output the sorted string.
Output result:
hnoptyOther Extensions
Python3 Examples