How to use Python to sort strings
Today, I would like to share with you how to use Python to achieve string sorting related knowledge points, detailed content, clear logic, I believe that most people still know too much about this knowledge, so share this article for your reference, I hope you can learn something after reading this article, let's take a look at it.
Description
1. When the sort () method sorts strings, it uses "ASCII character order" instead of the actual dictionary order.
2. If you need to sort in normal dictionary order, set the keyword parameter key to str.lower when the sort () method is called.
Example
Spam = ['elephants',' dogs', 'cats',' badgers', 'ants'] spam.sort () print (spam) prints the result: the [' ants', 'badgers',' cats', 'dogs',' elephants'] sort () method sorts strings using "ASCII character order" instead of the actual dictionary order. This means that uppercase letters come before lowercase letters. So when sorting, lowercase a comes after uppercase Z. Spam = ['Alice',' ants', 'Bob',' badgers', 'Carol',' cats'] spam.sort () print (spam) prints the result: ['Alice',' Bob', 'Carol',' ants', 'badgers',' cats'] if you need to sort it in normal dictionary order, set the keyword parameter key to str.lower when the sort () method is called. Spam = ['A','z','A','Z'] spam.sort (key=str.lower) print (spam) print the result: ['A','A','z','Z'] is all the content of the article "how to use Python to sort strings". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.