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}")
相关推荐
覆东流1 分钟前
第7天:Python小项目
开发语言·后端·python
a1117764 分钟前
Boxer 论文复刻(需要下载的文件都已放到压缩包)
python·开源·cv
不吃肥肉的傲寒5 分钟前
Graphify安装与结合claude code使用指南
java·python·ai编程·图搜索
djjdjdjdjjdj11 分钟前
golang如何编写SSL证书到期检测工具_golang SSL证书到期检测工具编写总结
jvm·数据库·python
axinawang16 分钟前
第2课: 与世界打招呼(输出)
python
2301_8135995516 分钟前
HTML5中Canvas局部刷新区域重绘的算法优化
jvm·数据库·python
m0_6028577616 分钟前
mysql如何防止用户通过子查询窃取权限_MySQL安全参数设置
jvm·数据库·python
我是无敌小恐龙22 分钟前
Java SE 零基础入门 Day05 类与对象核心详解(封装+构造方法+内存+变量)
java·开发语言·人工智能·python·机器学习·计算机视觉·数据挖掘
qq_1898070328 分钟前
Less如何处理CSS长文本换行_封装Mixin解决不同场景需求
jvm·数据库·python
小灰灰搞电子30 分钟前
Python self关键字详解及其应用
开发语言·python