Python Sort the Characters of a String Alphabetically
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
(
sorted_string
)
Code analysis:
original_string = "python": Define an original string"python"。sorted(original_string): When usingsorted()The function sorts the characters in the string and returns a list of characters in alphabetical order.''.join(sorted(original_string)): When usingjoin()The method joins the sorted character list into a new string.print(sorted_string): Print the sorted string.
Output result:
hnopty
Python3 Examples