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}")
相关推荐
站大爷IP27 分钟前
Python文件操作的"保险箱":with语句深度实战指南
python
运器12333 分钟前
【一起来学AI大模型】算法核心:数组/哈希表/树/排序/动态规划(LeetCode精练)
开发语言·人工智能·python·算法·ai·散列表·ai编程
strongwyy1 小时前
蓝牙墨水屏上位机学习(2)
学习
九皇叔叔1 小时前
(3)手摸手-学习 Vue3 之 变量声明【ref 和 reactive】区别
学习
致***锌2 小时前
期权标准化合约是什么?
笔记
Wilber的技术分享3 小时前
【机器学习实战笔记 14】集成学习:XGBoost算法(一) 原理简介与快速应用
人工智能·笔记·算法·随机森林·机器学习·集成学习·xgboost
巴里巴气3 小时前
selenium基础知识 和 模拟登录selenium版本
爬虫·python·selenium·爬虫模拟登录
19893 小时前
【零基础学AI】第26讲:循环神经网络(RNN)与LSTM - 文本生成
人工智能·python·rnn·神经网络·机器学习·tensorflow·lstm
JavaEdge在掘金3 小时前
Redis 数据倾斜?别慌!从成因到解决方案,一文帮你搞定
python
ansurfen3 小时前
我的第一个AI项目:从零搭建RAG知识库的踩坑之旅
python·llm