使用sorted()可对字符串字符或列表排序,按字母、长度或自定义规则。1. 字符排序用''.join(sorted(s));2. 列表排序默认按字典序,忽略大小写加key=str.lower;3. 按长度排序用key=len;4. 自定义规则可用lambda函数实现,如先按长度再按字母排序。

Python中实现字符串排序有多种方式,具体取决于你的排序需求,比如是按字母顺序、长度、还是自定义规则。下面介绍几种常见的字符串排序方法。
1. 使用sorted()函数对字符串中的字符排序
如果你希望对一个字符串内部的字符进行排序(例如将"bac"变成"abc"),可以使用sorted()函数:
示例:
s = "python"sorted_s = ''.join(sorted(s))
print(sorted_s) # 输出: 'hnopty'
注意:sorted()返回的是字符列表,需要用join()重新组合成字符串。
立即学习“Python免费学习笔记(深入)”;
2. 对字符串列表按字典序排序
当你有一个字符串列表,想按字母顺序排序,直接使用sorted()或list.sort()即可:
words = ["banana", "apple", "cherry"]sorted_words = sorted(words)
print(sorted_words) # 输出: ['apple', 'banana', 'cherry']
如果要忽略大小写,使用key=str.lower:
words = ["Banana", "apple", "Cherry"]sorted_words = sorted(words, key=str.lower)
print(sorted_words) # 输出: ['apple', 'Banana', 'Cherry']
3. 按字符串长度排序
使用key=len可以按字符串长度排序:
words = ["hi", "python", "code"]sorted_by_length = sorted(words, key=len)
print(sorted_by_length) # 输出: ['hi', 'code', 'python']
4. 自定义排序规则
你可以通过key参数传入自定义函数,比如先按长度排,再按字母序:
words = ["hi", "go", "code", "be"]sorted_custom = sorted(words, key=lambda x: (len(x), x))
print(sorted_custom) # 先按长度,再按字母:['be', 'go', 'hi', 'code']
基本上就这些常见用法。根据实际需求选择合适的方式即可,不复杂但容易忽略细节比如大小写和排序稳定性。










