• 技术文章 >Python技术 >Python基础教程

    Python如何实现字符串排序

    小妮浅浅小妮浅浅2021-07-27 09:32:00原创19310

    说明

    1、sort()方法对字符串排序时,使用“ASCII 字符顺序”,而不是实际的字典顺序。

    2、如果需要按照普通的字典顺序来排序,就在 sort()方法调用时,将关键字参数key设置为 str.lower。

    实例

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    spam = ['elephants', 'dogs', 'cats', 'badgers', 'ants']

    spam.sort()

    print(spam)

      

    打印结果:

    ['ants', 'badgers', 'cats', 'dogs', 'elephants']

      

    sort()方法对字符串排序时,使用“ASCII 字符顺序”,而不是实际的字典顺序。这意味着大写字母排在小写字母之前。因此在排序时,小写的 a 在大写的Z 之后。

      

    spam = ['Alice', 'ants', 'Bob', 'badgers', 'Carol', 'cats']

    spam.sort()

    print(spam)

      

    打印结果:

    ['Alice', 'Bob', 'Carol', 'ants', 'badgers', 'cats']

      

    如果需要按照普通的字典顺序来排序,就在 sort()方法调用时,将关键字参数key设置为 str.lower。

      

    spam = ['a', 'z', 'A', 'Z']

    spam.sort(key=str.lower)

    print(spam)

      

    打印结果:

    ['a', 'A', 'z', 'Z']

    以上就是Python实现字符串排序的方法,希望对大家有所帮助。更多Python学习指路:python基础教程

    本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

    专题推荐:python字符串
    上一篇:Python如何在列表中添加新值 下一篇:python标记删除如何实现?

    相关文章推荐

    • python中静态字符串的编码• python如何用方法更改字符串• python字符串需要注意的语法问题• python中如何使用RE正则表达检验字符串• python字符串的翻转实现的两种方法• python字符串的拆分与合并• Python字符串有哪几种表示形式• Python如何判定字符串被驻留• python字符串如何取值• python字符串格式化的方法整理• python字符串如何简单运算• php数组转json字符串• python使用f格式化字符串• python中str()函数转换字符串• php数组转字符串• JSON字符串如何转换成Python?• python提取字符串指定内容• python截取字符串中特定部分• python如何打印字符串• python字符串索引的用法

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网