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
相关推荐
Ray Liang11 分钟前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
AI攻城狮26 分钟前
如何给 AI Agent 做"断舍离":OpenClaw Session 自动清理实践
python
千寻girling29 分钟前
一份不可多得的 《 Python 》语言教程
人工智能·后端·python
AI攻城狮4 小时前
用 Playwright 实现博客一键发布到稀土掘金
python·自动化运维
曲幽4 小时前
FastAPI分布式系统实战:拆解分布式系统中常见问题及解决方案
redis·python·fastapi·web·httpx·lock·asyncio
孟健19 小时前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞21 小时前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽1 天前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers
敏编程1 天前
一天一个Python库:jsonschema - JSON 数据验证利器
python