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
相关推荐
databook9 小时前
Manim实现脉冲闪烁特效
后端·python·动效
程序设计实验室9 小时前
2025年了,在 Django 之外,Python Web 框架还能怎么选?
python
倔强青铜三11 小时前
苦练Python第46天:文件写入与上下文管理器
人工智能·python·面试
用户25191624271114 小时前
Python之语言特点
python
刘立军15 小时前
使用pyHugeGraph查询HugeGraph图数据
python·graphql
数据智能老司机18 小时前
精通 Python 设计模式——创建型设计模式
python·设计模式·架构
数据智能老司机19 小时前
精通 Python 设计模式——SOLID 原则
python·设计模式·架构
c8i20 小时前
django中的FBV 和 CBV
python·django
c8i20 小时前
python中的闭包和装饰器
python
这里有鱼汤1 天前
小白必看:QMT里的miniQMT入门教程
后端·python