python学习笔记—17—数据容器之字符串

  1. 字符串

(1) 字符串能通过下标索引来获取其中的元素

(2) 旧字符串无法修改特定下标的元素

(3) index------查找字符串中任意元素在整个字符串中的起始位置(单个字符或字符串都可以)

python 复制代码
tmp_str = "supercarrydoinb"
tmp_position1 = tmp_str.index("s")
tmp_position2 = tmp_str.index("doinb")
print(f"{tmp_position1}, {tmp_position2}")

(4) replace------将原字符串中部分字符串1改为字符串2,生成一个新的字符串,不修改原字符串

python 复制代码
tmp_str = "supercarrydoinb"
tmp_str1 = tmp_str.replace("doinb", "666")
print(f"{tmp_str1}")

(5) split------将字符串通过字符串中的子分割字符串分割成多个字符串存储到列表中,返回列表名

python 复制代码
tmp_str = "super carry doinb"
tmp_str1 = tmp_str.split(" ")
print(f"{tmp_str1}")

(6) strip

  1. 字符串.strip()

去除字符串前后的空格或回车符,将结果返回给新的字符串

python 复制代码
tmp_str = (" super carry doinb ")
tmp_str1 = tmp_str.strip()
print(f"{tmp_str1}")
  1. 字符串.strip(字符串1)

去除字符串前后的字符串1,将结果返回给新的字符串

python 复制代码
tmp_str = ("qwesuper carry doinbewq")
tmp_str1 = tmp_str.strip("qwe")
print(f"{tmp_str1}")

注意:对于strip中加参数,比如参数是ab,是分别去除a和b,而不是直接去除ab,非整体去除

(7) count------计算字符串中某个字符或部分字符串在整个字符串中的个数

python 复制代码
tmp_str = (" super carry doinb ")
tmp_cnt = tmp_str.count("do")
print(f"{tmp_cnt}")

(8) len------计算字符串中字符的个数

python 复制代码
tmp_str = ("supercarrydoinb")
tmp_len = len(tmp_str)
print(f"{tmp_len}")

(9) while循环

python 复制代码
tmp_str = ("supercarrydoinb")
tmp_cnt = 0
while tmp_cnt < len(tmp_str):
    print(f"{tmp_str[tmp_cnt]}")
    tmp_cnt += 1

(10) for循环

python 复制代码
tmp_str = ("supercarrydoinb")
for i in tmp_str:
    print(f"{i}")

(11) 字符串特点

字符串只能存储字符类型,且不可被修改

(12) 练习

python 复制代码
tmp_str = ("super carry doinb")
tmp_count = tmp_str.count("super")
print(f"{tmp_count}")
tmp_str1 = tmp_str.replace(" ", "|")
print(f"{tmp_str1}")
tmp_str2 = tmp_str1.split("|")
print(f"{tmp_str2}")
相关推荐
natide1 分钟前
词汇/表达差异-7-Alias覆盖率
人工智能·pytorch·python·深度学习·自然语言处理
艾莉丝努力练剑1 分钟前
Al Ping免费上新:GLM-4.7 && MiniMaxM2.1重磅上线,附独家使用教程
java·大数据·linux·运维·人工智能·python
拉姆哥的小屋2 分钟前
智能婴儿床监控系统
人工智能·python·深度学习
摸鱼仙人~3 分钟前
兼容OpenAI接口服务的实现类
开发语言·python
Y.O.U..4 分钟前
GO学习-io包常用接口
开发语言·学习·golang
semantist@语校4 分钟前
第五十七篇|东京银星日本语学校的数据建模:高密度城市中的学习节律、制度边界与 Prompt 接口设计
大数据·数据库·人工智能·学习·百度·prompt·知识图谱
代码游侠5 分钟前
学习笔记——TCP 传输控制协议
linux·网络·笔记·网络协议·学习·tcp/ip
Knight_AL5 分钟前
Java 可变参数 Object... args 详解:原理、用法与实战场景
java·开发语言·python
智算菩萨5 分钟前
迷宫生成算法:从生成树到均匀随机,再到工程化 Python 实现
python·算法·游戏
深蓝海拓7 分钟前
PySide6从0开始学习的笔记(十二) QProgressBar(进度条)
笔记·python·qt·学习·pyqt