• python--数据容器--str字符串


    目录

    字符串

    字符串查找

    字符串替换

    字符串的分割

    字符串的规整操作(去前后空格,只去字符串前后的,不去中间的)

    字符串的规整操作(指定的字符串)

    字符串遍历 ​编辑


    字符串

    尽管字符串看起来并不像:列表、元组那样,一看就是存放了许多数据的容器

    但不可否认的是,字符串同样也是数据容器的一员

    字符串是字符的容器。一个字符串可以存放任意数量的字符

    和其他容器如:列表、元组一样,字符串也可以通过下标进行访问

    从前向后,下标从0开始

    从后向前,下标从-1开始

    1. # 通过下标获取特定位置字符
    2. name = "itheima"
    3. print(name[0]) # 结果是 i
    4. print(name[-1]) # 结果 a

    字符串查找

    index

    字符串替换

    语法:字符串.replace(字符串1,字符串2)

    功能:将字符串内的全部: 字符串1,替换为字符串2

    注意:不是修改字符串本身,而是得到了个新的字符串

    字符串的分割

    语法:字符串.split(分隔符字符串)

    功能:按照指定的分割符字符串,将字符串划分为多个字符串,并存入列表对象

    注意:字符串本身不变,而是得到了一个列表对象

    字符串的规整操作(去前后空格,只去字符串前后的,不去中间的)

    语法:字符串.strip()

    字符串的规整操作(指定的字符串)

    语法: 字符串.strip(字符串)

    my_str.strip("12")

    注意 传入的是“12”  其实就是: “1”和“2”都会移除 是按照单个字符

    1. """
    2. 演示以数据容器的角色 学习字符串的相关操作
    3. """
    4. my_str = "itheima and itcast"
    5. # 通过下标索引取值
    6. value = my_str[2]
    7. value2 = my_str[-16]
    8. print(f"从字符串{my_str}取下标为2的元素,,值是:{value},取下标为-16 的元素,值是:{value2}")
    9. # 字符串不支持修改
    10. # my_str[2] = "H"
    11. # index方法
    12. value = my_str.index("and")
    13. print(f"在字符串{my_str}中查找and,其起始下标是:{value}")
    14. # replace方法
    15. new_my_str = my_str.replace("it", "程序")
    16. print(f"将字符串{my_str},进行替换后得到:{new_my_str}")
    17. # split方法
    18. my_str = "hello python itheima it"
    19. my_str_list = my_str.split(" ")
    20. print(f"将字符串{my_str}进行split切分后得到:{my_str_list},类型是{type(my_str_list)}")
    21. # strip 方法
    22. my_str = " itheima and itcast " #不传入参数 只去首尾空格
    23. my_str_strip = my_str.strip()
    24. print(my_str_strip)
    25. my_str = "12itheima and it cast21"
    26. new_my_str = my_str.strip("12")
    27. print(f"字符串{my_str}被strip('12')后结果是,:{new_my_str}")
    28. # 统计字符串中某字符串的出现次数, count
    29. my_str = "hello python itheima it ti"
    30. count = my_str.count("it")
    31. print(f"字符串{my_str}中it 出现的次数是{count}")
    32. #统计字符串的长度 len
    33. num = len(my_str)
    34. print(num)

    1. 从字符串itheima and itcast取下标为2的元素,,值是:h,取下标为-16 的元素,值是:h
    2. 在字符串itheima and itcast中查找and,其起始下标是:8
    3. 将字符串itheima and itcast,进行替换后得到:程序heima and 程序cast
    4. 将字符串hello python itheima it进行split切分后得到:['hello', 'python', 'itheima', 'it'],类型是<class 'list'>
    5. itheima and itcast
    6. 字符串12itheima and it cast21被strip('12')后结果是,:itheima and it cast
    7. 字符串hello python itheima it ti中it 出现的次数是2
    8. 26
    9. Process finished with exit code 0

    字符串遍历 

  • 相关阅读:
    一文读懂 Java 递归,你不得不会的技能
    奥迪AUDI EDI INVOIC发票报文详解
    数据库系统原理与应用教程(045)—— MySQL 查询(七):聚合函数
    产品代码都给你看了,可别再说不会DDD(五):请求处理流程
    Springboot给每个接口设置traceId,并添加到返回结果中
    20、商品微服务-web层实现
    音视频基础知识
    大数据量一次性导入MongoDB
    Stack Overflow使用总结
    Windows11系统提示msvcp140.dll丢失的解决方法,总共有四个解决方法
  • 原文地址:https://blog.csdn.net/baidu_41651554/article/details/126919932