Sorting Strings With sorted()
So, something like
string_number_value, and set this equal to
'34521'. And while you’re here, go ahead and make a more traditional string that’s going to contain just a sentence, like
'I like to sort'. Like before, save some sorted versions of the strings, so
sorted_string_number is just going to equal
sorted(), and then pass in
All right! Let’s take a look at what we’ve got. The
sorted_string_number looks like what you might expect.
sorted() returned a list containing each of the numbers, and they’re in ascending order.
You should note that
sorted() went through the string character by character, so it iterated over it just like a list. A good way to see this is to take a look at the
sorted_string that contains the sentence, because here you can see that you have spaces (
' ') that were sorted, and then you have each letter individually.
You now know that you can pass in lists, sets, tuples, or strings, and
sorted() will go ahead and sort those based on if they’re numbers or letters—or even words! You may have noticed up here that this
'I' was put before
'e', even though i comes after e in the alphabet. We’ll get into this later, when we talk about some of the common errors that you can run into with sorting.
Become a Member to join the conversation.