Python---字符串

字符串特点

  1. 只可以存储字符串

  2. 长度任意 (取决于内存大小)

  3. 支持下标索引

  4. 允许重复字符串存在

  5. 不可以修改 (增加或删除元素等)

  6. 支持for和while循环

字符串的下标索引

python 复制代码
# 字符串的下标索引
从前向后,下标从0开始
从后向前,下标从-1开始
语法:字符串[下标]

例子:

python 复制代码
my_str = "hello world"

# 取第一个
value1 = my_str[0]
print(value1)

# 取最后一个
value2 = my_str[-1]
print(value2)


my_str[2] = "2"  # 不能修改 

查找特定字符串的下表索引值---index

python 复制代码
# 查找特定字符串的下表索引值---index()
语法: 字符串.index(字符串)

print(my_str.index("h"))

字符串替换

python 复制代码
# 字符串的替换
语法: 字符串.replace(字符串1, 字符串2)   ----------- 字符串1替换为字符串2
注意:不是修改字符串本身,而是得到一个新的字符串

例子:

python 复制代码
my_str = "hello world"
new_str = my_str.replace('hello','hello1')
print(my_str)    # hello world
print(new_str)   # hello1 world

字符串的分割

python 复制代码
# 字符串的分割
语法: 字符串.split(分隔符字符串)
功能: 按照指定的分隔符字符串,将字符串划分为多个字符串,并存入列表对象中
注意:字符串本身不变,而是得到了一个列表对象

例子:

python 复制代码
my_str1 = "hello python hello world"
new_str1 = my_str1.split(" ")
print(new_str1)  # ['hello', 'python', 'hello', 'world']
print(my_str1)  # hello python hello world

字符串的规整操作

python 复制代码
# 字符串的规整操作(去前后空格)
语法:字符串.strip()

# 字符串的规整操作(去前后指定字符串)
语法:字符串.strip(字符串)

例子:

python 复制代码
my_str2 = "       hello python hello world         "
print(my_str2)
print(my_str2.strip())

my_str3 = "12hello python hello world21"
print(my_str3.strip("12"))

统计某字符串的出现次数 --- count

python 复制代码
my_str4 = "121232564862"
count = my_str4.count('2')
print(count)  # 4

统计字符串长度 --- len

python 复制代码
my_str5 = "121232564862"
num = len(my_str5)
print(num)  # 12
相关推荐
荣码13 小时前
GraphRAG:普通RAG只能回答"点"的问题,我踩了4个坑才搞懂
java·python
金銀銅鐵1 天前
[Python] 基于欧几里得算法,实现分数约分计算器
python·数学
Lyn_Li1 天前
Kaggle Top 5 | 198只股票、200条数据的金融预测——BattleFin高分方案从零复现
python·kaggle·比赛复盘·金融预测
小九九的爸爸1 天前
前端想要入门Agent开发,要具备哪些Python基础?
python·agent·ai编程
阿耶同学1 天前
手把手教你用 LangGraph 搭建三层嵌套 Agent 架构
python·程序员
花酒锄作田2 天前
Pydantic校验配置文件
python
hboot2 天前
AI工程师第四课 - 深度学习入门
pytorch·python·神经网络
ZhengEnCi2 天前
P2M-Matplotlib折线图完全指南-从数据可视化到趋势分析的Python绘图利器
python·matlab·数据可视化
ZhengEnCi3 天前
P2L-Matplotlib饼图完全指南-从数据可视化到图表定制的Python绘图利器
python·matlab
曲幽3 天前
你的REST接口还在“过度投喂”数据吗?——FastAPI + GraphQL实战避坑指南
python·fastapi·web·graphql·route·cors·rest·strawberry