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

- 和其它容器如:列表、元组一样,字符串也可以通过下标进行访问
-
同元组一样,字符串是一个:无法修改的数据容器
-
常用方法

-
代码案例
| my_str = "itheima and itcast" |
| |
| value = my_str[2] |
| value2 = my_str[-16] |
| print(f"从字符串{my_str}取下标为2的元素,。值是:{value},取下标为-16的元素。值是:{value2}") |
| |
| |
| |
| |
| |
| value = my_str.index("and") |
| print(f"在字符串{my_str}中查找and,其起始下标是:{value}") |
| |
| |
| new_my_str = my_str.replace("it", "程序") |
| print(f"将字符串{my_str},进行替换后得到:{new_my_str}") |
| |
| |
| my_str = "hello python itheima itcast" |
| my_str_list = my_str.split(" ") |
| print(f"将字符串{my_str}进行split切分后得到:{my_str_list}, 类型是:{type(my_str_list)}") |
| |
| |
| my_str = " itheima and itcast " |
| new_my_str = my_str.strip() |
| print(f"字符串{my_str}被strip后,结果:{new_my_str}") |
| |
| my_str = "12itheima and itcast21" |
| new_my_str = my_str.strip("12") |
| print(f"字符串{my_str}被strip('12')后,结果:{new_my_str}") |
| |
| |
| my_str = "itheima and itcast" |
| count = my_str.count("it") |
| print(f"字符串{my_str}中it出现的次数是:{count}") |
| |
| |
| num = len(my_str) |
| print(f"字符串{my_str}的长度是:{num}") |
| my_str = "itheima itcast boxuegu" |
| |
| num = my_str.count("it") |
| print(f"字符串{my_str}中有{num}个it字符") |
| |
| |
| new_my_str = my_str.replace(" ", "|") |
| print(f"字符串{my_str}被替换空格后,结果是:{new_my_str}") |
| |
| |
| my_str_list = new_my_str.split("|") |
| print(f"字符串{new_my_str}按照|分割后结果是:{my_str_list}") |
| 只可以存储字符串 |
| 长度任意(取决于内存大小) |
| 支持下标索引 |
| 允许重复字符串存在 |
| 不可以修改(增加或删除元素等) |
| 支持for循环 |
| |
| 基本和列表、元组相同 |
| 不同与列表和元组的在于:字符串容器可以容纳的类型是单一的,只能是字符串类型。 |
| 不同于列表,相同于元组的在于:字符串不可修改 |
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术