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
相关推荐
知识中的海王2 小时前
js逆向入门图灵爬虫练习平台第六题
python
碳基学AI3 小时前
北京大学DeepSeek内部研讨系列:AI在新媒体运营中的应用与挑战|122页PPT下载方法
大数据·人工智能·python·算法·ai·新媒体运营·产品运营
forestsea3 小时前
Python进阶编程总结
开发语言·python·notepad++
袖清暮雨3 小时前
Python刷题笔记
笔记·python·算法
乌旭4 小时前
AI芯片混战:GPU vs TPU vs NPU的算力与能效博弈
人工智能·pytorch·python·深度学习·机器学习·ai·ai编程
MinggeQingchun5 小时前
Python - 爬虫-网页抓取数据-库requests
爬虫·python·requests
拓端研究室TRL5 小时前
Python贝叶斯回归、强化学习分析医疗健康数据拟合截断删失数据与参数估计3实例
开发语言·人工智能·python·数据挖掘·回归
wolf犭良6 小时前
27、Python 数据库操作入门(SQLite)从基础到实战精讲
数据库·python·sqlite
sa100276 小时前
基于Python的网络爬虫技术研究
开发语言·爬虫·python