Python Sort String Alphabetically

Document 对象参考手册Python3 Examples

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)

Code explanation:

  1. original_string = "python": Define an original string"python"。
  2. sorted(original_string): Usesorted()function to sort the characters in a string, returning a list of characters arranged alphabetically.
  3. ''.join(sorted(original_string)): Usejoin()method to join the sorted character list into a new string.
  4. print(sorted_string): Output the sorted string.

Output result:

hnopty

Document 对象参考手册Python3 Examples

Other Extensions