Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Sort the Characters of a String Alphabetically

Python Sort the Characters of a String Alphabetically

Document Object Reference Manual Python3 Examples

In Python, we can use the built-in sorted() The function sorts the characters in a string alphabetically.sorted() The function returns a list containing the characters in ascending order. If we want a sorted string, we can use the join() method to join the characters in the list.

Example

Raw strings

original_string

=

"python"

Sort the string

sorted_string

=

''

.

join

(

sorted

(

original_string

)

)

Print the sorted string

print

(

sorted_string

)

Code analysis:

  1. original_string = "python": Define an original string "python"。
  2. sorted(original_string): When using sorted() The function sorts the characters in the string and returns a list of characters in alphabetical order.
  3. ''.join(sorted(original_string)): When using join() The method joins the sorted character list into a new string.
  4. print(sorted_string): Print the sorted string.

Output result:

hnopty

Document Object Reference Manual Python3 Examples