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}")
相关推荐
椎49512 分钟前
JSONUtil工具包大致学习使用
学习
数据科学小丫30 分钟前
Python 数据存储操作_数据存储、补充知识点:Python 与 MySQL交互
数据库·python·mysql
Knight_AL33 分钟前
Nacos 启动问题 Failed to create database ’D:\nacos\nacos\data\derby-data’
开发语言·数据库·python
leiming61 小时前
CAN 通信协议学习讲义(带图文 + C 语言代码)
c语言·开发语言·学习
Heartache boy1 小时前
野火STM32_HAL库版课程笔记-ADC多通道采集热敏、光敏、反射传感器(轮询)
笔记·stm32·单片机
yoothey2 小时前
Java字节流与字符流核心笔记(问答+考点复盘)
java·开发语言·笔记
查古穆2 小时前
python进阶-Pydantic模型
开发语言·python
星空2 小时前
RAG学习第一节
学习
知识分享小能手2 小时前
MongoDB入门学习教程,从入门到精通,MongoDB入门指南 —— 知识点详解(2)
数据库·学习·mongodb
老师好,我是刘同学2 小时前
force与deposit在SystemVerilog中的区别详解
笔记